DynamoDB examples using AWS CLI with Bash script - AWS SDK Code Examples

There are more AWS SDK examples available in the AWS Doc SDK Examples GitHub repo.

DynamoDB examples using AWS CLI with Bash script

The following code examples show you how to perform actions and implement common scenarios by using the AWS Command Line Interface with Bash script with DynamoDB.

Basics are code examples that show you how to perform the essential operations within a service.

Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios.

Scenarios are code examples that show you how to accomplish specific tasks by calling multiple functions within a service or combined with other AWS services.

Each example includes a link to the complete source code, where you can find instructions on how to set up and run the code in context.

Basics

The following code example shows how to:

  • Create a table that can hold movie data.

  • Put, get, and update a single movie in the table.

  • Write movie data to the table from a sample JSON file.

  • Query for movies that were released in a given year.

  • Scan for movies that were released in a range of years.

  • Delete a movie from the table, then delete the table.

AWS CLI with Bash script
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

The DynamoDB getting started scenario.

############################################################################### # function dynamodb_getting_started_movies # # Scenario to create an Amazon DynamoDB table and perform a series of operations on the table. # # Returns: # 0 - If successful. # 1 - If an error occurred. ############################################################################### function dynamodb_getting_started_movies() { source ./dynamodb_operations.sh key_schema_json_file="dynamodb_key_schema.json" attribute_definitions_json_file="dynamodb_attr_def.json" item_json_file="movie_item.json" key_json_file="movie_key.json" batch_json_file="batch.json" attribute_names_json_file="attribute_names.json" attributes_values_json_file="attribute_values.json" echo_repeat "*" 88 echo echo "Welcome to the Amazon DynamoDB getting started demo." echo echo_repeat "*" 88 echo local table_name echo -n "Enter a name for a new DynamoDB table: " get_input table_name=$get_input_result echo '[ {"AttributeName": "year", "KeyType": "HASH"}, {"AttributeName": "title", "KeyType": "RANGE"} ]' >"$key_schema_json_file" echo '[ {"AttributeName": "year", "AttributeType": "N"}, {"AttributeName": "title", "AttributeType": "S"} ]' >"$attribute_definitions_json_file" if dynamodb_create_table -n "$table_name" -a "$attribute_definitions_json_file" \ -k "$key_schema_json_file" 1>/dev/null; then echo "Created a DynamoDB table named $table_name" else errecho "The table failed to create. This demo will exit." clean_up return 1 fi echo "Waiting for the table to become active...." if dynamodb_wait_table_active -n "$table_name"; then echo "The table is now active." else errecho "The table failed to become active. This demo will exit." cleanup "$table_name" return 1 fi echo echo_repeat "*" 88 echo echo -n "Enter the title of a movie you want to add to the table: " get_input local added_title added_title=$get_input_result local added_year get_int_input "What year was it released? " added_year=$get_input_result local rating get_float_input "On a scale of 1 - 10, how do you rate it? " "1" "10" rating=$get_input_result local plot echo -n "Summarize the plot for me: " get_input plot=$get_input_result echo '{ "year": {"N" :"'"$added_year"'"}, "title": {"S" : "'"$added_title"'"}, "info": {"M" : {"plot": {"S" : "'"$plot"'"}, "rating": {"N" :"'"$rating"'"} } } }' >"$item_json_file" if dynamodb_put_item -n "$table_name" -i "$item_json_file"; then echo "The movie '$added_title' was successfully added to the table '$table_name'." else errecho "Put item failed. This demo will exit." clean_up "$table_name" return 1 fi echo echo_repeat "*" 88 echo echo "Let's update your movie '$added_title'." get_float_input "You rated it $rating, what new rating would you give it? " "1" "10" rating=$get_input_result echo -n "You summarized the plot as '$plot'." echo "What would you say now? " get_input plot=$get_input_result echo '{ "year": {"N" :"'"$added_year"'"}, "title": {"S" : "'"$added_title"'"} }' >"$key_json_file" echo '{ ":r": {"N" :"'"$rating"'"}, ":p": {"S" : "'"$plot"'"} }' >"$item_json_file" local update_expression="SET info.rating = :r, info.plot = :p" if dynamodb_update_item -n "$table_name" -k "$key_json_file" -e "$update_expression" -v "$item_json_file"; then echo "Updated '$added_title' with new attributes." else errecho "Update item failed. This demo will exit." clean_up "$table_name" return 1 fi echo echo_repeat "*" 88 echo echo "We will now use batch write to upload 150 movie entries into the table." local batch_json for batch_json in movie_files/movies_*.json; do echo "{ \"$table_name\" : $(<"$batch_json") }" >"$batch_json_file" if dynamodb_batch_write_item -i "$batch_json_file" 1>/dev/null; then echo "Entries in $batch_json added to table." else errecho "Batch write failed. This demo will exit." clean_up "$table_name" return 1 fi done local title="The Lord of the Rings: The Fellowship of the Ring" local year="2001" if get_yes_no_input "Let's move on...do you want to get info about '$title'? (y/n) "; then echo '{ "year": {"N" :"'"$year"'"}, "title": {"S" : "'"$title"'"} }' >"$key_json_file" local info info=$(dynamodb_get_item -n "$table_name" -k "$key_json_file") # shellcheck disable=SC2181 if [[ ${?} -ne 0 ]]; then errecho "Get item failed. This demo will exit." clean_up "$table_name" return 1 fi echo "Here is what I found:" echo "$info" fi local ask_for_year=true while [[ "$ask_for_year" == true ]]; do echo "Let's get a list of movies released in a given year." get_int_input "Enter a year between 1972 and 2018: " "1972" "2018" year=$get_input_result echo '{ "#n": "year" }' >"$attribute_names_json_file" echo '{ ":v": {"N" :"'"$year"'"} }' >"$attributes_values_json_file" response=$(dynamodb_query -n "$table_name" -k "#n=:v" -a "$attribute_names_json_file" -v "$attributes_values_json_file") # shellcheck disable=SC2181 if [[ ${?} -ne 0 ]]; then errecho "Query table failed. This demo will exit." clean_up "$table_name" return 1 fi echo "Here is what I found:" echo "$response" if ! get_yes_no_input "Try another year? (y/n) "; then ask_for_year=false fi done echo "Now let's scan for movies released in a range of years. Enter a year: " get_int_input "Enter a year between 1972 and 2018: " "1972" "2018" local start=$get_input_result get_int_input "Enter another year: " "1972" "2018" local end=$get_input_result echo '{ "#n": "year" }' >"$attribute_names_json_file" echo '{ ":v1": {"N" : "'"$start"'"}, ":v2": {"N" : "'"$end"'"} }' >"$attributes_values_json_file" response=$(dynamodb_scan -n "$table_name" -f "#n BETWEEN :v1 AND :v2" -a "$attribute_names_json_file" -v "$attributes_values_json_file") # shellcheck disable=SC2181 if [[ ${?} -ne 0 ]]; then errecho "Scan table failed. This demo will exit." clean_up "$table_name" return 1 fi echo "Here is what I found:" echo "$response" echo echo_repeat "*" 88 echo echo "Let's remove your movie '$added_title' from the table." if get_yes_no_input "Do you want to remove '$added_title'? (y/n) "; then echo '{ "year": {"N" :"'"$added_year"'"}, "title": {"S" : "'"$added_title"'"} }' >"$key_json_file" if ! dynamodb_delete_item -n "$table_name" -k "$key_json_file"; then errecho "Delete item failed. This demo will exit." clean_up "$table_name" return 1 fi fi if get_yes_no_input "Do you want to delete the table '$table_name'? (y/n) "; then if ! clean_up "$table_name"; then return 1 fi else if ! clean_up; then return 1 fi fi return 0 }

The DynamoDB functions used in this scenario.

############################################################################### # function dynamodb_create_table # # This function creates an Amazon DynamoDB table. # # Parameters: # -n table_name -- The name of the table to create. # -a attribute_definitions -- JSON file path of a list of attributes and their types. # -k key_schema -- JSON file path of a list of attributes and their key types. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function dynamodb_create_table() { local table_name attribute_definitions key_schema response local option OPTARG # Required to use getopts command in a function. ####################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_create_table" echo "Creates an Amazon DynamoDB table with on-demand billing." echo " -n table_name -- The name of the table to create." echo " -a attribute_definitions -- JSON file path of a list of attributes and their types." echo " -k key_schema -- JSON file path of a list of attributes and their key types." echo "" } # Retrieve the calling parameters. while getopts "n:a:k:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; a) attribute_definitions="${OPTARG}" ;; k) key_schema="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$attribute_definitions" ]]; then errecho "ERROR: You must provide an attribute definitions json file path the -a parameter." usage return 1 fi if [[ -z "$key_schema" ]]; then errecho "ERROR: You must provide a key schema json file path the -k parameter." usage return 1 fi iecho "Parameters:\n" iecho " table_name: $table_name" iecho " attribute_definitions: $attribute_definitions" iecho " key_schema: $key_schema" iecho "" response=$(aws dynamodb create-table \ --table-name "$table_name" \ --attribute-definitions file://"$attribute_definitions" \ --billing-mode PAY_PER_REQUEST \ --key-schema file://"$key_schema" ) local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports create-table operation failed.$response" return 1 fi return 0 } ############################################################################### # function dynamodb_describe_table # # This function returns the status of a DynamoDB table. # # Parameters: # -n table_name -- The name of the table. # # Response: # - TableStatus: # And: # 0 - Table is active. # 1 - If it fails. ############################################################################### function dynamodb_describe_table { local table_name local option OPTARG # Required to use getopts command in a function. ####################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_describe_table" echo "Describe the status of a DynamoDB table." echo " -n table_name -- The name of the table." echo "" } # Retrieve the calling parameters. while getopts "n:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi local table_status table_status=$( aws dynamodb describe-table \ --table-name "$table_name" \ --output text \ --query 'Table.TableStatus' ) local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log "$error_code" errecho "ERROR: AWS reports describe-table operation failed.$table_status" return 1 fi echo "$table_status" return 0 } ############################################################################## # function dynamodb_put_item # # This function puts an item into a DynamoDB table. # # Parameters: # -n table_name -- The name of the table. # -i item -- Path to json file containing the item values. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################## function dynamodb_put_item() { local table_name item response local option OPTARG # Required to use getopts command in a function. ####################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_put_item" echo "Put an item into a DynamoDB table." echo " -n table_name -- The name of the table." echo " -i item -- Path to json file containing the item values." echo "" } while getopts "n:i:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; i) item="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$item" ]]; then errecho "ERROR: You must provide an item with the -i parameter." usage return 1 fi iecho "Parameters:\n" iecho " table_name: $table_name" iecho " item: $item" iecho "" iecho "" response=$(aws dynamodb put-item \ --table-name "$table_name" \ --item file://"$item") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports put-item operation failed.$response" return 1 fi return 0 } ############################################################################## # function dynamodb_update_item # # This function updates an item in a DynamoDB table. # # # Parameters: # -n table_name -- The name of the table. # -k keys -- Path to json file containing the keys that identify the item to update. # -e update expression -- An expression that defines one or more attributes to be updated. # -v values -- Path to json file containing the update values. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################# function dynamodb_update_item() { local table_name keys update_expression values response local option OPTARG # Required to use getopts command in a function. ####################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_update_item" echo "Update an item in a DynamoDB table." echo " -n table_name -- The name of the table." echo " -k keys -- Path to json file containing the keys that identify the item to update." echo " -e update expression -- An expression that defines one or more attributes to be updated." echo " -v values -- Path to json file containing the update values." echo "" } while getopts "n:k:e:v:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; k) keys="${OPTARG}" ;; e) update_expression="${OPTARG}" ;; v) values="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$keys" ]]; then errecho "ERROR: You must provide a keys json file path the -k parameter." usage return 1 fi if [[ -z "$update_expression" ]]; then errecho "ERROR: You must provide an update expression with the -e parameter." usage return 1 fi if [[ -z "$values" ]]; then errecho "ERROR: You must provide a values json file path the -v parameter." usage return 1 fi iecho "Parameters:\n" iecho " table_name: $table_name" iecho " keys: $keys" iecho " update_expression: $update_expression" iecho " values: $values" response=$(aws dynamodb update-item \ --table-name "$table_name" \ --key file://"$keys" \ --update-expression "$update_expression" \ --expression-attribute-values file://"$values") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports update-item operation failed.$response" return 1 fi return 0 } ############################################################################## # function dynamodb_batch_write_item # # This function writes a batch of items into a DynamoDB table. # # Parameters: # -i item -- Path to json file containing the items to write. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################ function dynamodb_batch_write_item() { local item response local option OPTARG # Required to use getopts command in a function. ####################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_batch_write_item" echo "Write a batch of items into a DynamoDB table." echo " -i item -- Path to json file containing the items to write." echo "" } while getopts "i:h" option; do case "${option}" in i) item="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$item" ]]; then errecho "ERROR: You must provide an item with the -i parameter." usage return 1 fi iecho "Parameters:\n" iecho " table_name: $table_name" iecho " item: $item" iecho "" response=$(aws dynamodb batch-write-item \ --request-items file://"$item") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports batch-write-item operation failed.$response" return 1 fi return 0 } ############################################################################# # function dynamodb_get_item # # This function gets an item from a DynamoDB table. # # Parameters: # -n table_name -- The name of the table. # -k keys -- Path to json file containing the keys that identify the item to get. # [-q query] -- Optional JMESPath query expression. # # Returns: # The item as text output. # And: # 0 - If successful. # 1 - If it fails. ############################################################################ function dynamodb_get_item() { local table_name keys query response local option OPTARG # Required to use getopts command in a function. # ###################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_get_item" echo "Get an item from a DynamoDB table." echo " -n table_name -- The name of the table." echo " -k keys -- Path to json file containing the keys that identify the item to get." echo " [-q query] -- Optional JMESPath query expression." echo "" } query="" while getopts "n:k:q:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; k) keys="${OPTARG}" ;; q) query="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$keys" ]]; then errecho "ERROR: You must provide a keys json file path the -k parameter." usage return 1 fi if [[ -n "$query" ]]; then response=$(aws dynamodb get-item \ --table-name "$table_name" \ --key file://"$keys" \ --output text \ --query "$query") else response=$( aws dynamodb get-item \ --table-name "$table_name" \ --key file://"$keys" \ --output text ) fi local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports get-item operation failed.$response" return 1 fi if [[ -n "$query" ]]; then echo "$response" | sed "/^\t/s/\t//1" # Remove initial tab that the JMSEPath query inserts on some strings. else echo "$response" fi return 0 } ############################################################################# # function dynamodb_query # # This function queries a DynamoDB table. # # Parameters: # -n table_name -- The name of the table. # -k key_condition_expression -- The key condition expression. # -a attribute_names -- Path to JSON file containing the attribute names. # -v attribute_values -- Path to JSON file containing the attribute values. # [-p projection_expression] -- Optional projection expression. # # Returns: # The items as json output. # And: # 0 - If successful. # 1 - If it fails. ########################################################################### function dynamodb_query() { local table_name key_condition_expression attribute_names attribute_values projection_expression response local option OPTARG # Required to use getopts command in a function. # ###################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_query" echo "Query a DynamoDB table." echo " -n table_name -- The name of the table." echo " -k key_condition_expression -- The key condition expression." echo " -a attribute_names -- Path to JSON file containing the attribute names." echo " -v attribute_values -- Path to JSON file containing the attribute values." echo " [-p projection_expression] -- Optional projection expression." echo "" } while getopts "n:k:a:v:p:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; k) key_condition_expression="${OPTARG}" ;; a) attribute_names="${OPTARG}" ;; v) attribute_values="${OPTARG}" ;; p) projection_expression="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$key_condition_expression" ]]; then errecho "ERROR: You must provide a key condition expression with the -k parameter." usage return 1 fi if [[ -z "$attribute_names" ]]; then errecho "ERROR: You must provide a attribute names with the -a parameter." usage return 1 fi if [[ -z "$attribute_values" ]]; then errecho "ERROR: You must provide a attribute values with the -v parameter." usage return 1 fi if [[ -z "$projection_expression" ]]; then response=$(aws dynamodb query \ --table-name "$table_name" \ --key-condition-expression "$key_condition_expression" \ --expression-attribute-names file://"$attribute_names" \ --expression-attribute-values file://"$attribute_values") else response=$(aws dynamodb query \ --table-name "$table_name" \ --key-condition-expression "$key_condition_expression" \ --expression-attribute-names file://"$attribute_names" \ --expression-attribute-values file://"$attribute_values" \ --projection-expression "$projection_expression") fi local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports query operation failed.$response" return 1 fi echo "$response" return 0 } ############################################################################# # function dynamodb_scan # # This function scans a DynamoDB table. # # Parameters: # -n table_name -- The name of the table. # -f filter_expression -- The filter expression. # -a expression_attribute_names -- Path to JSON file containing the expression attribute names. # -v expression_attribute_values -- Path to JSON file containing the expression attribute values. # [-p projection_expression] -- Optional projection expression. # # Returns: # The items as json output. # And: # 0 - If successful. # 1 - If it fails. ########################################################################### function dynamodb_scan() { local table_name filter_expression expression_attribute_names expression_attribute_values projection_expression response local option OPTARG # Required to use getopts command in a function. # ###################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_scan" echo "Scan a DynamoDB table." echo " -n table_name -- The name of the table." echo " -f filter_expression -- The filter expression." echo " -a expression_attribute_names -- Path to JSON file containing the expression attribute names." echo " -v expression_attribute_values -- Path to JSON file containing the expression attribute values." echo " [-p projection_expression] -- Optional projection expression." echo "" } while getopts "n:f:a:v:p:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; f) filter_expression="${OPTARG}" ;; a) expression_attribute_names="${OPTARG}" ;; v) expression_attribute_values="${OPTARG}" ;; p) projection_expression="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$filter_expression" ]]; then errecho "ERROR: You must provide a filter expression with the -f parameter." usage return 1 fi if [[ -z "$expression_attribute_names" ]]; then errecho "ERROR: You must provide expression attribute names with the -a parameter." usage return 1 fi if [[ -z "$expression_attribute_values" ]]; then errecho "ERROR: You must provide expression attribute values with the -v parameter." usage return 1 fi if [[ -z "$projection_expression" ]]; then response=$(aws dynamodb scan \ --table-name "$table_name" \ --filter-expression "$filter_expression" \ --expression-attribute-names file://"$expression_attribute_names" \ --expression-attribute-values file://"$expression_attribute_values") else response=$(aws dynamodb scan \ --table-name "$table_name" \ --filter-expression "$filter_expression" \ --expression-attribute-names file://"$expression_attribute_names" \ --expression-attribute-values file://"$expression_attribute_values" \ --projection-expression "$projection_expression") fi local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports scan operation failed.$response" return 1 fi echo "$response" return 0 } ############################################################################## # function dynamodb_delete_item # # This function deletes an item from a DynamoDB table. # # Parameters: # -n table_name -- The name of the table. # -k keys -- Path to json file containing the keys that identify the item to delete. # # Returns: # 0 - If successful. # 1 - If it fails. ########################################################################### function dynamodb_delete_item() { local table_name keys response local option OPTARG # Required to use getopts command in a function. # ###################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_delete_item" echo "Delete an item from a DynamoDB table." echo " -n table_name -- The name of the table." echo " -k keys -- Path to json file containing the keys that identify the item to delete." echo "" } while getopts "n:k:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; k) keys="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$keys" ]]; then errecho "ERROR: You must provide a keys json file path the -k parameter." usage return 1 fi iecho "Parameters:\n" iecho " table_name: $table_name" iecho " keys: $keys" iecho "" response=$(aws dynamodb delete-item \ --table-name "$table_name" \ --key file://"$keys") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports delete-item operation failed.$response" return 1 fi return 0 } ############################################################################### # function dynamodb_delete_table # # This function deletes a DynamoDB table. # # Parameters: # -n table_name -- The name of the table to delete. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function dynamodb_delete_table() { local table_name response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function dynamodb_delete_table" echo "Deletes an Amazon DynamoDB table." echo " -n table_name -- The name of the table to delete." echo "" } # Retrieve the calling parameters. while getopts "n:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi iecho "Parameters:\n" iecho " table_name: $table_name" iecho "" response=$(aws dynamodb delete-table \ --table-name "$table_name") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports delete-table operation failed.$response" return 1 fi return 0 }

The utility functions used in this scenario.

############################################################################### # function iecho # # This function enables the script to display the specified text only if # the global variable $VERBOSE is set to true. ############################################################################### function iecho() { if [[ $VERBOSE == true ]]; then echo "$@" fi } ############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }

Actions

The following code example shows how to use BatchGetItem.

AWS CLI with Bash script
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

############################################################################# # function dynamodb_batch_get_item # # This function gets a batch of items from a DynamoDB table. # # Parameters: # -i item -- Path to json file containing the keys of the items to get. # # Returns: # The items as json output. # And: # 0 - If successful. # 1 - If it fails. ########################################################################## function dynamodb_batch_get_item() { local item response local option OPTARG # Required to use getopts command in a function. ####################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_batch_get_item" echo "Get a batch of items from a DynamoDB table." echo " -i item -- Path to json file containing the keys of the items to get." echo "" } while getopts "i:h" option; do case "${option}" in i) item="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$item" ]]; then errecho "ERROR: You must provide an item with the -i parameter." usage return 1 fi response=$(aws dynamodb batch-get-item \ --request-items file://"$item") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports batch-get-item operation failed.$response" return 1 fi echo "$response" return 0 }

The utility functions used in this example.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • For API details, see BatchGetItem in AWS CLI Command Reference.

The following code example shows how to use BatchWriteItem.

AWS CLI with Bash script
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

############################################################################## # function dynamodb_batch_write_item # # This function writes a batch of items into a DynamoDB table. # # Parameters: # -i item -- Path to json file containing the items to write. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################ function dynamodb_batch_write_item() { local item response local option OPTARG # Required to use getopts command in a function. ####################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_batch_write_item" echo "Write a batch of items into a DynamoDB table." echo " -i item -- Path to json file containing the items to write." echo "" } while getopts "i:h" option; do case "${option}" in i) item="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$item" ]]; then errecho "ERROR: You must provide an item with the -i parameter." usage return 1 fi iecho "Parameters:\n" iecho " table_name: $table_name" iecho " item: $item" iecho "" response=$(aws dynamodb batch-write-item \ --request-items file://"$item") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports batch-write-item operation failed.$response" return 1 fi return 0 }

The utility functions used in this example.

############################################################################### # function iecho # # This function enables the script to display the specified text only if # the global variable $VERBOSE is set to true. ############################################################################### function iecho() { if [[ $VERBOSE == true ]]; then echo "$@" fi } ############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }

The following code example shows how to use CreateTable.

AWS CLI with Bash script
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

############################################################################### # function dynamodb_create_table # # This function creates an Amazon DynamoDB table. # # Parameters: # -n table_name -- The name of the table to create. # -a attribute_definitions -- JSON file path of a list of attributes and their types. # -k key_schema -- JSON file path of a list of attributes and their key types. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function dynamodb_create_table() { local table_name attribute_definitions key_schema response local option OPTARG # Required to use getopts command in a function. ####################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_create_table" echo "Creates an Amazon DynamoDB table with on-demand billing." echo " -n table_name -- The name of the table to create." echo " -a attribute_definitions -- JSON file path of a list of attributes and their types." echo " -k key_schema -- JSON file path of a list of attributes and their key types." echo "" } # Retrieve the calling parameters. while getopts "n:a:k:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; a) attribute_definitions="${OPTARG}" ;; k) key_schema="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$attribute_definitions" ]]; then errecho "ERROR: You must provide an attribute definitions json file path the -a parameter." usage return 1 fi if [[ -z "$key_schema" ]]; then errecho "ERROR: You must provide a key schema json file path the -k parameter." usage return 1 fi iecho "Parameters:\n" iecho " table_name: $table_name" iecho " attribute_definitions: $attribute_definitions" iecho " key_schema: $key_schema" iecho "" response=$(aws dynamodb create-table \ --table-name "$table_name" \ --attribute-definitions file://"$attribute_definitions" \ --billing-mode PAY_PER_REQUEST \ --key-schema file://"$key_schema" ) local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports create-table operation failed.$response" return 1 fi return 0 }

The utility functions used in this example.

############################################################################### # function iecho # # This function enables the script to display the specified text only if # the global variable $VERBOSE is set to true. ############################################################################### function iecho() { if [[ $VERBOSE == true ]]; then echo "$@" fi } ############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • For API details, see CreateTable in AWS CLI Command Reference.

The following code example shows how to use DeleteItem.

AWS CLI with Bash script
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

############################################################################## # function dynamodb_delete_item # # This function deletes an item from a DynamoDB table. # # Parameters: # -n table_name -- The name of the table. # -k keys -- Path to json file containing the keys that identify the item to delete. # # Returns: # 0 - If successful. # 1 - If it fails. ########################################################################### function dynamodb_delete_item() { local table_name keys response local option OPTARG # Required to use getopts command in a function. # ###################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_delete_item" echo "Delete an item from a DynamoDB table." echo " -n table_name -- The name of the table." echo " -k keys -- Path to json file containing the keys that identify the item to delete." echo "" } while getopts "n:k:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; k) keys="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$keys" ]]; then errecho "ERROR: You must provide a keys json file path the -k parameter." usage return 1 fi iecho "Parameters:\n" iecho " table_name: $table_name" iecho " keys: $keys" iecho "" response=$(aws dynamodb delete-item \ --table-name "$table_name" \ --key file://"$keys") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports delete-item operation failed.$response" return 1 fi return 0 }

The utility functions used in this example.

############################################################################### # function iecho # # This function enables the script to display the specified text only if # the global variable $VERBOSE is set to true. ############################################################################### function iecho() { if [[ $VERBOSE == true ]]; then echo "$@" fi } ############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • For API details, see DeleteItem in AWS CLI Command Reference.

The following code example shows how to use DeleteTable.

AWS CLI with Bash script
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

############################################################################### # function dynamodb_delete_table # # This function deletes a DynamoDB table. # # Parameters: # -n table_name -- The name of the table to delete. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function dynamodb_delete_table() { local table_name response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function dynamodb_delete_table" echo "Deletes an Amazon DynamoDB table." echo " -n table_name -- The name of the table to delete." echo "" } # Retrieve the calling parameters. while getopts "n:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi iecho "Parameters:\n" iecho " table_name: $table_name" iecho "" response=$(aws dynamodb delete-table \ --table-name "$table_name") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports delete-table operation failed.$response" return 1 fi return 0 }

The utility functions used in this example.

############################################################################### # function iecho # # This function enables the script to display the specified text only if # the global variable $VERBOSE is set to true. ############################################################################### function iecho() { if [[ $VERBOSE == true ]]; then echo "$@" fi } ############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • For API details, see DeleteTable in AWS CLI Command Reference.

The following code example shows how to use DescribeTable.

AWS CLI with Bash script
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

############################################################################### # function dynamodb_describe_table # # This function returns the status of a DynamoDB table. # # Parameters: # -n table_name -- The name of the table. # # Response: # - TableStatus: # And: # 0 - Table is active. # 1 - If it fails. ############################################################################### function dynamodb_describe_table { local table_name local option OPTARG # Required to use getopts command in a function. ####################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_describe_table" echo "Describe the status of a DynamoDB table." echo " -n table_name -- The name of the table." echo "" } # Retrieve the calling parameters. while getopts "n:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi local table_status table_status=$( aws dynamodb describe-table \ --table-name "$table_name" \ --output text \ --query 'Table.TableStatus' ) local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log "$error_code" errecho "ERROR: AWS reports describe-table operation failed.$table_status" return 1 fi echo "$table_status" return 0 }

The utility functions used in this example.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • For API details, see DescribeTable in AWS CLI Command Reference.

The following code example shows how to use GetItem.

AWS CLI with Bash script
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

############################################################################# # function dynamodb_get_item # # This function gets an item from a DynamoDB table. # # Parameters: # -n table_name -- The name of the table. # -k keys -- Path to json file containing the keys that identify the item to get. # [-q query] -- Optional JMESPath query expression. # # Returns: # The item as text output. # And: # 0 - If successful. # 1 - If it fails. ############################################################################ function dynamodb_get_item() { local table_name keys query response local option OPTARG # Required to use getopts command in a function. # ###################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_get_item" echo "Get an item from a DynamoDB table." echo " -n table_name -- The name of the table." echo " -k keys -- Path to json file containing the keys that identify the item to get." echo " [-q query] -- Optional JMESPath query expression." echo "" } query="" while getopts "n:k:q:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; k) keys="${OPTARG}" ;; q) query="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$keys" ]]; then errecho "ERROR: You must provide a keys json file path the -k parameter." usage return 1 fi if [[ -n "$query" ]]; then response=$(aws dynamodb get-item \ --table-name "$table_name" \ --key file://"$keys" \ --output text \ --query "$query") else response=$( aws dynamodb get-item \ --table-name "$table_name" \ --key file://"$keys" \ --output text ) fi local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports get-item operation failed.$response" return 1 fi if [[ -n "$query" ]]; then echo "$response" | sed "/^\t/s/\t//1" # Remove initial tab that the JMSEPath query inserts on some strings. else echo "$response" fi return 0 }

The utility functions used in this example.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • For API details, see GetItem in AWS CLI Command Reference.

The following code example shows how to use ListTables.

AWS CLI with Bash script
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

############################################################################## # function dynamodb_list_tables # # This function lists all the tables in a DynamoDB. # # Returns: # 0 - If successful. # 1 - If it fails. ########################################################################### function dynamodb_list_tables() { response=$(aws dynamodb list-tables \ --output text \ --query "TableNames") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports batch-write-item operation failed.$response" return 1 fi echo "$response" | tr -s "[:space:]" "\n" return 0 }

The utility functions used in this example.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • For API details, see ListTables in AWS CLI Command Reference.

The following code example shows how to use PutItem.

AWS CLI with Bash script
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

############################################################################## # function dynamodb_put_item # # This function puts an item into a DynamoDB table. # # Parameters: # -n table_name -- The name of the table. # -i item -- Path to json file containing the item values. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################## function dynamodb_put_item() { local table_name item response local option OPTARG # Required to use getopts command in a function. ####################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_put_item" echo "Put an item into a DynamoDB table." echo " -n table_name -- The name of the table." echo " -i item -- Path to json file containing the item values." echo "" } while getopts "n:i:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; i) item="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$item" ]]; then errecho "ERROR: You must provide an item with the -i parameter." usage return 1 fi iecho "Parameters:\n" iecho " table_name: $table_name" iecho " item: $item" iecho "" iecho "" response=$(aws dynamodb put-item \ --table-name "$table_name" \ --item file://"$item") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports put-item operation failed.$response" return 1 fi return 0 }

The utility functions used in this example.

############################################################################### # function iecho # # This function enables the script to display the specified text only if # the global variable $VERBOSE is set to true. ############################################################################### function iecho() { if [[ $VERBOSE == true ]]; then echo "$@" fi } ############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • For API details, see PutItem in AWS CLI Command Reference.

The following code example shows how to use Query.

AWS CLI with Bash script
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

############################################################################# # function dynamodb_query # # This function queries a DynamoDB table. # # Parameters: # -n table_name -- The name of the table. # -k key_condition_expression -- The key condition expression. # -a attribute_names -- Path to JSON file containing the attribute names. # -v attribute_values -- Path to JSON file containing the attribute values. # [-p projection_expression] -- Optional projection expression. # # Returns: # The items as json output. # And: # 0 - If successful. # 1 - If it fails. ########################################################################### function dynamodb_query() { local table_name key_condition_expression attribute_names attribute_values projection_expression response local option OPTARG # Required to use getopts command in a function. # ###################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_query" echo "Query a DynamoDB table." echo " -n table_name -- The name of the table." echo " -k key_condition_expression -- The key condition expression." echo " -a attribute_names -- Path to JSON file containing the attribute names." echo " -v attribute_values -- Path to JSON file containing the attribute values." echo " [-p projection_expression] -- Optional projection expression." echo "" } while getopts "n:k:a:v:p:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; k) key_condition_expression="${OPTARG}" ;; a) attribute_names="${OPTARG}" ;; v) attribute_values="${OPTARG}" ;; p) projection_expression="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$key_condition_expression" ]]; then errecho "ERROR: You must provide a key condition expression with the -k parameter." usage return 1 fi if [[ -z "$attribute_names" ]]; then errecho "ERROR: You must provide a attribute names with the -a parameter." usage return 1 fi if [[ -z "$attribute_values" ]]; then errecho "ERROR: You must provide a attribute values with the -v parameter." usage return 1 fi if [[ -z "$projection_expression" ]]; then response=$(aws dynamodb query \ --table-name "$table_name" \ --key-condition-expression "$key_condition_expression" \ --expression-attribute-names file://"$attribute_names" \ --expression-attribute-values file://"$attribute_values") else response=$(aws dynamodb query \ --table-name "$table_name" \ --key-condition-expression "$key_condition_expression" \ --expression-attribute-names file://"$attribute_names" \ --expression-attribute-values file://"$attribute_values" \ --projection-expression "$projection_expression") fi local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports query operation failed.$response" return 1 fi echo "$response" return 0 }

The utility functions used in this example.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • For API details, see Query in AWS CLI Command Reference.

The following code example shows how to use Scan.

AWS CLI with Bash script
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

############################################################################# # function dynamodb_scan # # This function scans a DynamoDB table. # # Parameters: # -n table_name -- The name of the table. # -f filter_expression -- The filter expression. # -a expression_attribute_names -- Path to JSON file containing the expression attribute names. # -v expression_attribute_values -- Path to JSON file containing the expression attribute values. # [-p projection_expression] -- Optional projection expression. # # Returns: # The items as json output. # And: # 0 - If successful. # 1 - If it fails. ########################################################################### function dynamodb_scan() { local table_name filter_expression expression_attribute_names expression_attribute_values projection_expression response local option OPTARG # Required to use getopts command in a function. # ###################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_scan" echo "Scan a DynamoDB table." echo " -n table_name -- The name of the table." echo " -f filter_expression -- The filter expression." echo " -a expression_attribute_names -- Path to JSON file containing the expression attribute names." echo " -v expression_attribute_values -- Path to JSON file containing the expression attribute values." echo " [-p projection_expression] -- Optional projection expression." echo "" } while getopts "n:f:a:v:p:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; f) filter_expression="${OPTARG}" ;; a) expression_attribute_names="${OPTARG}" ;; v) expression_attribute_values="${OPTARG}" ;; p) projection_expression="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$filter_expression" ]]; then errecho "ERROR: You must provide a filter expression with the -f parameter." usage return 1 fi if [[ -z "$expression_attribute_names" ]]; then errecho "ERROR: You must provide expression attribute names with the -a parameter." usage return 1 fi if [[ -z "$expression_attribute_values" ]]; then errecho "ERROR: You must provide expression attribute values with the -v parameter." usage return 1 fi if [[ -z "$projection_expression" ]]; then response=$(aws dynamodb scan \ --table-name "$table_name" \ --filter-expression "$filter_expression" \ --expression-attribute-names file://"$expression_attribute_names" \ --expression-attribute-values file://"$expression_attribute_values") else response=$(aws dynamodb scan \ --table-name "$table_name" \ --filter-expression "$filter_expression" \ --expression-attribute-names file://"$expression_attribute_names" \ --expression-attribute-values file://"$expression_attribute_values" \ --projection-expression "$projection_expression") fi local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports scan operation failed.$response" return 1 fi echo "$response" return 0 }

The utility functions used in this example.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • For API details, see Scan in AWS CLI Command Reference.

The following code example shows how to use UpdateItem.

AWS CLI with Bash script
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

############################################################################## # function dynamodb_update_item # # This function updates an item in a DynamoDB table. # # # Parameters: # -n table_name -- The name of the table. # -k keys -- Path to json file containing the keys that identify the item to update. # -e update expression -- An expression that defines one or more attributes to be updated. # -v values -- Path to json file containing the update values. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################# function dynamodb_update_item() { local table_name keys update_expression values response local option OPTARG # Required to use getopts command in a function. ####################################### # Function usage explanation ####################################### function usage() { echo "function dynamodb_update_item" echo "Update an item in a DynamoDB table." echo " -n table_name -- The name of the table." echo " -k keys -- Path to json file containing the keys that identify the item to update." echo " -e update expression -- An expression that defines one or more attributes to be updated." echo " -v values -- Path to json file containing the update values." echo "" } while getopts "n:k:e:v:h" option; do case "${option}" in n) table_name="${OPTARG}" ;; k) keys="${OPTARG}" ;; e) update_expression="${OPTARG}" ;; v) values="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$table_name" ]]; then errecho "ERROR: You must provide a table name with the -n parameter." usage return 1 fi if [[ -z "$keys" ]]; then errecho "ERROR: You must provide a keys json file path the -k parameter." usage return 1 fi if [[ -z "$update_expression" ]]; then errecho "ERROR: You must provide an update expression with the -e parameter." usage return 1 fi if [[ -z "$values" ]]; then errecho "ERROR: You must provide a values json file path the -v parameter." usage return 1 fi iecho "Parameters:\n" iecho " table_name: $table_name" iecho " keys: $keys" iecho " update_expression: $update_expression" iecho " values: $values" response=$(aws dynamodb update-item \ --table-name "$table_name" \ --key file://"$keys" \ --update-expression "$update_expression" \ --expression-attribute-values file://"$values") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports update-item operation failed.$response" return 1 fi return 0 }

The utility functions used in this example.

############################################################################### # function iecho # # This function enables the script to display the specified text only if # the global variable $VERBOSE is set to true. ############################################################################### function iecho() { if [[ $VERBOSE == true ]]; then echo "$@" fi } ############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
  • For API details, see UpdateItem in AWS CLI Command Reference.

Scenarios

The following code example shows how to work with advanced Global Secondary Index configurations.

  • Create a table with multiple GSIs.

  • Create a table with on-demand capacity and GSI.

  • Put items into a table with multiple GSIs.

  • Query multiple GSIs with different conditions.

AWS CLI with Bash script

Create a table with multiple GSIs.

# Create a table with multiple GSIs aws dynamodb create-table \ --table-name MusicLibrary \ --attribute-definitions \ AttributeName=Artist,AttributeType=S \ AttributeName=SongTitle,AttributeType=S \ AttributeName=AlbumTitle,AttributeType=S \ AttributeName=Genre,AttributeType=S \ AttributeName=Year,AttributeType=N \ --key-schema \ AttributeName=Artist,KeyType=HASH \ AttributeName=SongTitle,KeyType=RANGE \ --billing-mode PAY_PER_REQUEST \ --global-secondary-indexes \ "[ { \"IndexName\": \"AlbumIndex\", \"KeySchema\": [{\"AttributeName\":\"AlbumTitle\",\"KeyType\":\"HASH\"}], \"Projection\": {\"ProjectionType\":\"ALL\"} }, { \"IndexName\": \"GenreYearIndex\", \"KeySchema\": [ {\"AttributeName\":\"Genre\",\"KeyType\":\"HASH\"}, {\"AttributeName\":\"Year\",\"KeyType\":\"RANGE\"} ], \"Projection\": {\"ProjectionType\":\"INCLUDE\",\"NonKeyAttributes\":[\"Artist\",\"SongTitle\"]} } ]"

Create a table with on-demand capacity and GSI.

# Create a table with on-demand capacity and GSI aws dynamodb create-table \ --table-name MusicOnDemand \ --attribute-definitions \ AttributeName=Artist,AttributeType=S \ AttributeName=SongTitle,AttributeType=S \ AttributeName=Genre,AttributeType=S \ --key-schema \ AttributeName=Artist,KeyType=HASH \ AttributeName=SongTitle,KeyType=RANGE \ --billing-mode PAY_PER_REQUEST \ --global-secondary-indexes \ "[ { \"IndexName\": \"GenreIndex\", \"KeySchema\": [{\"AttributeName\":\"Genre\",\"KeyType\":\"HASH\"}], \"Projection\": {\"ProjectionType\":\"ALL\"} } ]"

Put items into a table with multiple GSIs.

# Add items to MusicLibrary table aws dynamodb put-item \ --table-name MusicLibrary \ --item '{ "Artist": {"S": "The Beatles"}, "SongTitle": {"S": "Hey Jude"}, "AlbumTitle": {"S": "Past Masters"}, "Genre": {"S": "Rock"}, "Year": {"N": "1968"} }' aws dynamodb put-item \ --table-name MusicLibrary \ --item '{ "Artist": {"S": "Miles Davis"}, "SongTitle": {"S": "So What"}, "AlbumTitle": {"S": "Kind of Blue"}, "Genre": {"S": "Jazz"}, "Year": {"N": "1959"} }'

Query items from a table with multiple GSIs.

# Query the AlbumIndex GSI echo "Querying AlbumIndex GSI:" aws dynamodb query \ --table-name MusicLibrary \ --index-name AlbumIndex \ --key-condition-expression "AlbumTitle = :album" \ --expression-attribute-values '{":album":{"S":"Kind of Blue"}}' # Query the GenreYearIndex GSI with a range condition echo "Querying GenreYearIndex GSI with range condition:" aws dynamodb query \ --table-name MusicLibrary \ --index-name GenreYearIndex \ --key-condition-expression "Genre = :genre AND #yr > :year" \ --expression-attribute-names '{"#yr": "Year"}' \ --expression-attribute-values '{":genre":{"S":"Rock"},":year":{"N":"1965"}}'

The following code example shows how to manage the complete lifecycle of Global Secondary Indexes.

  • Create a table with a Global Secondary Index.

  • Add a new GSI to an existing table.

  • Update (increase) GSI warm throughput.

  • Query data using GSIs.

  • Delete a GSI.

AWS CLI with Bash script

Create a table with a Global Secondary Index.

# Create a table with a GSI aws dynamodb create-table \ --table-name MusicCollection \ --attribute-definitions \ AttributeName=Artist,AttributeType=S \ AttributeName=SongTitle,AttributeType=S \ AttributeName=AlbumTitle,AttributeType=S \ --key-schema \ AttributeName=Artist,KeyType=HASH \ AttributeName=SongTitle,KeyType=RANGE \ --billing-mode PAY_PER_REQUEST \ --global-secondary-indexes \ "IndexName=AlbumIndex,\ KeySchema=[{AttributeName=AlbumTitle,KeyType=HASH}],\ Projection={ProjectionType=ALL}"

Add a new (on-demand) GSI to an existing table.

# Add a new GSI to an existing table aws dynamodb update-table \ --table-name MusicCollection \ --attribute-definitions \ AttributeName=Genre,AttributeType=S \ --global-secondary-index-updates \ "[{\"Create\":{\"IndexName\":\"GenreIndex\",\ \"KeySchema\":[{\"AttributeName\":\"Genre\",\"KeyType\":\"HASH\"}],\ \"Projection\":{\"ProjectionType\":\"ALL\"}}}]"

Update (increase) GSI warm throughput.

# Increase the warm throughput of a GSI (default values are 12k reads, 4k writes) aws dynamodb update-table \ --table-name MusicCollection \ --global-secondary-index-updates \ "[{\"Update\":{\"IndexName\":\"AlbumIndex\",\ \"WarmThroughput\":{\"ReadUnitsPerSecond\":15000,\"WriteUnitsPerSecond\":6000}}}]"

Query data using GSIs.

# Query the AlbumIndex GSI aws dynamodb query \ --table-name MusicCollection \ --index-name AlbumIndex \ --key-condition-expression "AlbumTitle = :album" \ --expression-attribute-values '{":album":{"S":"Let It Be"}}' # Query the GenreIndex GSI aws dynamodb query \ --table-name MusicCollection \ --index-name GenreIndex \ --key-condition-expression "Genre = :genre" \ --expression-attribute-values '{":genre":{"S":"Jazz"}}'

Delete a GSI.

# Delete a GSI from a table aws dynamodb update-table \ --table-name MusicCollection \ --global-secondary-index-updates \ "[{\"Delete\":{\"IndexName\":\"GenreIndex\"}}]"

The following code example shows how to manage the complete lifecycle of resource-based policies for DynamoDB tables.

  • Create a table with a resource policy.

  • Get a resource policy.

  • Update a resource policy.

  • Delete a resource policy.

AWS CLI with Bash script

Create a table with a resource policy.

# Step 1: Create a DynamoDB table aws dynamodb create-table \ --table-name MusicCollection \ --attribute-definitions \ AttributeName=Artist,AttributeType=S \ AttributeName=SongTitle,AttributeType=S \ --key-schema \ AttributeName=Artist,KeyType=HASH \ AttributeName=SongTitle,KeyType=RANGE \ --billing-mode PAY_PER_REQUEST # Step 2: Create a resource-based policy document cat > policy.json << 'EOF' { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::123456789012:role/DynamoDBReadOnly" }, "Action": [ "dynamodb:GetItem", "dynamodb:BatchGetItem", "dynamodb:Query", "dynamodb:Scan" ], "Resource": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection" } ] } EOF # Step 3: Attach the resource-based policy to the table aws dynamodb put-resource-policy \ --resource-arn arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection \ --policy file://policy.json

Get a resource policy.

# Get the resource-based policy attached to a table aws dynamodb get-resource-policy \ --resource-arn arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection

Update a resource policy.

# Step 1: Create an updated policy document cat > updated-policy.json << 'EOF' { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": [ "arn:aws:iam::123456789012:role/DynamoDBReadOnly", "arn:aws:iam::123456789012:role/DynamoDBAnalytics" ] }, "Action": [ "dynamodb:GetItem", "dynamodb:BatchGetItem", "dynamodb:Query", "dynamodb:Scan" ], "Resource": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection" } ] } EOF # Step 2: Update the resource-based policy on the table aws dynamodb put-resource-policy \ --resource-arn arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection \ --policy file://updated-policy.json

Delete a resource policy.

# Delete the resource-based policy from a table aws dynamodb delete-resource-policy \ --resource-arn arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection

The following code example shows how to implement Attribute-Based Access Control (ABAC) for DynamoDB.

  • Create an IAM policy for ABAC.

  • Create tables with tags for different departments.

  • List and filter tables based on tags.

AWS CLI with Bash script

Create an IAM policy for ABAC.

# Step 1: Create a policy document for ABAC cat > abac-policy.json << 'EOF' { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "dynamodb:GetItem", "dynamodb:BatchGetItem", "dynamodb:Query", "dynamodb:Scan" ], "Resource": "arn:aws:dynamodb:*:*:table/*", "Condition": { "StringEquals": { "aws:ResourceTag/Department": "${aws:PrincipalTag/Department}" } } }, { "Effect": "Allow", "Action": [ "dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:DeleteItem", "dynamodb:BatchWriteItem" ], "Resource": "arn:aws:dynamodb:*:*:table/*", "Condition": { "StringEquals": { "aws:ResourceTag/Department": "${aws:PrincipalTag/Department}", "aws:ResourceTag/Environment": "Development" } } } ] } EOF # Step 2: Create the IAM policy aws iam create-policy \ --policy-name DynamoDBDepartmentBasedAccess \ --policy-document file://abac-policy.json

Create tables with tags for different departments.

# Create a DynamoDB table with tags for ABAC aws dynamodb create-table \ --table-name FinanceData \ --attribute-definitions \ AttributeName=RecordID,AttributeType=S \ --key-schema \ AttributeName=RecordID,KeyType=HASH \ --billing-mode PAY_PER_REQUEST \ --tags \ Key=Department,Value=Finance \ Key=Environment,Value=Development # Create another table with different tags aws dynamodb create-table \ --table-name MarketingData \ --attribute-definitions \ AttributeName=RecordID,AttributeType=S \ --key-schema \ AttributeName=RecordID,KeyType=HASH \ --billing-mode PAY_PER_REQUEST \ --tags \ Key=Department,Value=Marketing \ Key=Environment,Value=Production

List and filter tables based on tags.

# List all DynamoDB tables echo "Listing all tables:" aws dynamodb list-tables # Get ARNs for all tables echo -e "\nGetting ARNs for all tables:" TABLE_ARNS=$(aws dynamodb list-tables --query "TableNames[*]" --output text | xargs -I {} aws dynamodb describe-table --table-name {} --query "Table.TableArn" --output text) # For each table ARN, list its tags echo -e "\nListing tags for each table:" for ARN in $TABLE_ARNS; do TABLE_NAME=$(echo $ARN | awk -F/ '{print $2}') echo -e "\nTags for table: $TABLE_NAME" aws dynamodb list-tags-of-resource --resource-arn $ARN done # Example: Find tables with a specific tag echo -e "\nFinding tables with Environment=Production tag:" for ARN in $TABLE_ARNS; do TABLE_NAME=$(echo $ARN | awk -F/ '{print $2}') TAGS=$(aws dynamodb list-tags-of-resource --resource-arn $ARN --query "Tags[?Key=='Environment' && Value=='Production']" --output text) if [ ! -z "$TAGS" ]; then echo "Table with Production tag: $TABLE_NAME" fi done

The following code example shows how to create and query tables with Local Secondary Indexes.

  • Create a table with a Local Secondary Index (LSI).

  • Create a table with multiple LSIs with different projection types.

  • Query data using LSIs.

AWS CLI with Bash script

Create a table with a Local Secondary Index.

# Create a table with a Local Secondary Index aws dynamodb create-table \ --table-name CustomerOrders \ --attribute-definitions \ AttributeName=CustomerID,AttributeType=S \ AttributeName=OrderID,AttributeType=S \ AttributeName=OrderDate,AttributeType=S \ --key-schema \ AttributeName=CustomerID,KeyType=HASH \ AttributeName=OrderID,KeyType=RANGE \ --local-secondary-indexes \ "IndexName=OrderDateIndex,\ KeySchema=[{AttributeName=CustomerID,KeyType=HASH},{AttributeName=OrderDate,KeyType=RANGE}],\ Projection={ProjectionType=ALL}" \ --billing-mode PAY_PER_REQUEST

Create a table with multiple LSIs.

# Create a table with multiple Local Secondary Indexes aws dynamodb create-table \ --table-name CustomerDetails \ --attribute-definitions \ AttributeName=CustomerID,AttributeType=S \ AttributeName=Name,AttributeType=S \ AttributeName=Email,AttributeType=S \ AttributeName=RegistrationDate,AttributeType=S \ --key-schema \ AttributeName=CustomerID,KeyType=HASH \ AttributeName=Name,KeyType=RANGE \ --local-secondary-indexes \ "[ { \"IndexName\": \"EmailIndex\", \"KeySchema\": [ {\"AttributeName\":\"CustomerID\",\"KeyType\":\"HASH\"}, {\"AttributeName\":\"Email\",\"KeyType\":\"RANGE\"} ], \"Projection\": {\"ProjectionType\":\"INCLUDE\",\"NonKeyAttributes\":[\"Address\",\"Phone\"]} }, { \"IndexName\": \"RegistrationIndex\", \"KeySchema\": [ {\"AttributeName\":\"CustomerID\",\"KeyType\":\"HASH\"}, {\"AttributeName\":\"RegistrationDate\",\"KeyType\":\"RANGE\"} ], \"Projection\": {\"ProjectionType\":\"KEYS_ONLY\"} } ]" \ --billing-mode PAY_PER_REQUEST

Query data using LSIs.

# Query the OrderDateIndex LSI aws dynamodb query \ --table-name CustomerOrders \ --index-name OrderDateIndex \ --key-condition-expression "CustomerID = :custId AND OrderDate BETWEEN :date1 AND :date2" \ --expression-attribute-values '{ ":custId": {"S": "C1"}, ":date1": {"S": "2023-01-01"}, ":date2": {"S": "2023-02-01"} }' # Query with a filter expression aws dynamodb query \ --table-name CustomerOrders \ --index-name OrderDateIndex \ --key-condition-expression "CustomerID = :custId" \ --filter-expression "Amount > :amount" \ --expression-attribute-values '{ ":custId": {"S": "C1"}, ":amount": {"N": "150"} }'
  • For API details, see the following topics in AWS CLI Command Reference.

The following code example shows how to manage DynamoDB Streams and Time-to-Live features.

  • Create a table with Streams enabled.

  • Describe Streams.

  • Create a Lambda function for processing Streams.

  • Enable TTL on a table.

  • Add items with TTL attributes.

  • Describe TTL settings.

AWS CLI with Bash script

Create a table with Streams enabled.

# Create a table with DynamoDB Streams enabled aws dynamodb create-table \ --table-name StreamsDemo \ --attribute-definitions \ AttributeName=ID,AttributeType=S \ --key-schema \ AttributeName=ID,KeyType=HASH \ --billing-mode PAY_PER_REQUEST \ --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES

Describe Streams.

# Get information about the stream aws dynamodb describe-table \ --table-name StreamsDemo \ --query "Table.StreamSpecification" # Get the stream ARN STREAM_ARN=$(aws dynamodb describe-table \ --table-name StreamsDemo \ --query "Table.LatestStreamArn" \ --output text) echo "Stream ARN: $STREAM_ARN" # Describe the stream aws dynamodbstreams describe-stream \ --stream-arn $STREAM_ARN

Create a Lambda function for Streams.

# Step 1: Create an IAM role for the Lambda function cat > trust-policy.json << 'EOF' { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } EOF aws iam create-role \ --role-name DynamoDBStreamsLambdaRole \ --assume-role-policy-document file://trust-policy.json # Step 2: Attach permissions to the role aws iam attach-role-policy \ --role-name DynamoDBStreamsLambdaRole \ --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaDynamoDBExecutionRole # Step 3: Create a Lambda function (code would be in a separate file) echo "Lambda function creation would be done separately with appropriate code" # Step 4: Create an event source mapping echo "Example command to create event source mapping:" echo "aws lambda create-event-source-mapping \\" echo " --function-name ProcessDynamoDBRecords \\" echo " --event-source $STREAM_ARN \\" echo " --batch-size 100 \\" echo " --starting-position LATEST"

Enable TTL on a table.

# Create a table for TTL demonstration aws dynamodb create-table \ --table-name TTLDemo \ --attribute-definitions \ AttributeName=ID,AttributeType=S \ --key-schema \ AttributeName=ID,KeyType=HASH \ --billing-mode PAY_PER_REQUEST # Wait for table to become active aws dynamodb wait table-exists --table-name TTLDemo # Enable TTL on the table aws dynamodb update-time-to-live \ --table-name TTLDemo \ --time-to-live-specification "Enabled=true, AttributeName=ExpirationTime"

Add items with TTL attributes.

# Calculate expiration time (current time + 1 day in seconds) EXPIRATION_TIME=$(date -d "+1 day" +%s) # Add an item with TTL attribute aws dynamodb put-item \ --table-name TTLDemo \ --item '{ "ID": {"S": "item1"}, "Data": {"S": "This item will expire in 1 day"}, "ExpirationTime": {"N": "'$EXPIRATION_TIME'"} }' # Add an item that expires in 1 hour EXPIRATION_TIME_HOUR=$(date -d "+1 hour" +%s) aws dynamodb put-item \ --table-name TTLDemo \ --item '{ "ID": {"S": "item2"}, "Data": {"S": "This item will expire in 1 hour"}, "ExpirationTime": {"N": "'$EXPIRATION_TIME_HOUR'"} }'

Describe TTL settings.

# Describe TTL settings for a table aws dynamodb describe-time-to-live \ --table-name TTLDemo

The following code example shows how to manage DynamoDB global tables with multi-region replication.

  • Create a table with multi-region replication.

  • Put and get items from replica tables.

  • Remove replicas.

AWS CLI with Bash script

Create a table with multi-region replication.

# Step 1: Create a new table in us-west-2 aws dynamodb create-table \ --table-name MusicTable \ --attribute-definitions \ AttributeName=Artist,AttributeType=S \ AttributeName=SongTitle,AttributeType=S \ --key-schema \ AttributeName=Artist,KeyType=HASH \ AttributeName=SongTitle,KeyType=RANGE \ --billing-mode PAY_PER_REQUEST \ --region us-west-2 # Step 2: Create replicas in us-east-1 and us-east-2 aws dynamodb update-table \ --table-name MusicTable \ --replica-updates '[{"Create": {"RegionName": "us-east-1"}}, {"Create": {"RegionName": "us-east-2"}}]' \ --multi-region-consistency STRONG \ --region us-west-2

Describe the multi-region table.

# Describe the base table aws dynamodb describe-table --table-name MusicTable --region us-west-2

Put items in a replica table.

# Write a single item to one of the replica tables. aws dynamodb put-item \ --table-name MusicTable \ --item '{"Artist": {"S":"item_1"},"SongTitle": {"S":"Song Value 1"}}' \ --region us-east-2

Get items from replica tables.

# Get item from the other two replicas aws dynamodb get-item \ --table-name MusicTable \ --key '{"Artist": {"S":"item_1"},"SongTitle": {"S":"Song Value 1"}}' \ --consistent-read \ --region us-east-1 aws dynamodb get-item \ --table-name MusicTable \ --key '{"Artist": {"S":"item_1"},"SongTitle": {"S":"Song Value 1"}}' \ --consistent-read \ --region us-west-2

Remove replicas.

# Remove the replica tables. aws dynamodb update-table \ --table-name MusicTable \ --replica-updates '[{"Delete": {"RegionName": "us-east-2"}}, {"Delete": {"RegionName": "us-east-1"}}]' \ --region us-west-2

The following code example shows how to manage tags for DynamoDB resources.

  • Create a table with tags.

  • List tags for a resource.

  • Add tags to a resource.

  • Remove tags from a resource.

  • Filter tables by tags.

AWS CLI with Bash script

Create a table with tags.

# Create a table with tags aws dynamodb create-table \ --table-name TaggedTable \ --attribute-definitions \ AttributeName=ID,AttributeType=S \ --key-schema \ AttributeName=ID,KeyType=HASH \ --billing-mode PAY_PER_REQUEST \ --tags \ Key=Environment,Value=Production \ Key=Project,Value=Analytics \ Key=Owner,Value=DataTeam

List tags for a resource.

# Get the table ARN TABLE_ARN=$(aws dynamodb describe-table \ --table-name TaggedTable \ --query "Table.TableArn" \ --output text) # List tags for the table aws dynamodb list-tags-of-resource \ --resource-arn $TABLE_ARN

Add tags to a resource.

# Add tags to an existing table aws dynamodb tag-resource \ --resource-arn $TABLE_ARN \ --tags \ Key=CostCenter,Value=12345 \ Key=BackupSchedule,Value=Daily

Remove tags from a resource.

# Remove tags from a table aws dynamodb untag-resource \ --resource-arn $TABLE_ARN \ --tag-keys Owner BackupSchedule

Filter tables by tags.

# Create another table with different tags aws dynamodb create-table \ --table-name AnotherTaggedTable \ --attribute-definitions \ AttributeName=ID,AttributeType=S \ --key-schema \ AttributeName=ID,KeyType=HASH \ --billing-mode PAY_PER_REQUEST \ --tags \ Key=Environment,Value=Development \ Key=Project,Value=Testing # Wait for table to become active aws dynamodb wait table-exists --table-name AnotherTaggedTable # List all tables echo "All tables:" aws dynamodb list-tables # Get ARNs for all tables echo -e "\nFiltering tables by Environment=Production tag:" TABLE_ARNS=$(aws dynamodb list-tables --query "TableNames[*]" --output text | xargs -I {} aws dynamodb describe-table --table-name {} --query "Table.TableArn" --output text) # Find tables with specific tag for ARN in $TABLE_ARNS; do TABLE_NAME=$(echo $ARN | awk -F/ '{print $2}') TAGS=$(aws dynamodb list-tags-of-resource --resource-arn $ARN --query "Tags[?Key=='Environment' && Value=='Production']" --output text) if [ ! -z "$TAGS" ]; then echo "Table with Production tag: $TABLE_NAME" fi done

The following code example shows how to manage encryption options for DynamoDB tables.

  • Create a table with default encryption.

  • Create a table with a customer managed CMK.

  • Update table encryption settings.

  • Describe table encryption.

AWS CLI with Bash script

Create a table with default encryption.

# Create a table with default encryption (AWS owned key) aws dynamodb create-table \ --table-name CustomerData \ --attribute-definitions \ AttributeName=CustomerID,AttributeType=S \ --key-schema \ AttributeName=CustomerID,KeyType=HASH \ --billing-mode PAY_PER_REQUEST \ --sse-specification Enabled=true,SSEType=KMS

Create a table with a customer managed CMK.

# Step 1: Create a customer managed key in KMS aws kms create-key \ --description "Key for DynamoDB table encryption" \ --key-usage ENCRYPT_DECRYPT \ --customer-master-key-spec SYMMETRIC_DEFAULT # Store the key ID for later use KEY_ID=$(aws kms list-keys --query "Keys[?contains(KeyArn, 'Key for DynamoDB')].KeyId" --output text) # Step 2: Create a table with the customer managed key aws dynamodb create-table \ --table-name SensitiveData \ --attribute-definitions \ AttributeName=RecordID,AttributeType=S \ --key-schema \ AttributeName=RecordID,KeyType=HASH \ --billing-mode PAY_PER_REQUEST \ --sse-specification Enabled=true,SSEType=KMS,KMSMasterKeyId=$KEY_ID

Update table encryption.

# Update a table to use a different KMS key aws dynamodb update-table \ --table-name CustomerData \ --sse-specification Enabled=true,SSEType=KMS,KMSMasterKeyId=$KEY_ID

Describe table encryption.

# Describe the table to see encryption settings aws dynamodb describe-table \ --table-name CustomerData \ --query "Table.SSEDescription"