Creating the DynamoDB Table
To begin, we create a DynamoDB table using the AWS DynamoDB table resource in Terraform. In this example, we create a table named “cars” that holds data about vehicles. The table requires a name and a hash key that serves as the primary key—in our case, the vehicle identification number (VIN). Additionally, an attribute block is specified to detail the attribute (VIN) and the billing mode is set to on-demand (PAY_PER_REQUEST). Below is the Terraform configuration for creating the “cars” DynamoDB table with on-demand billing:Remember, on-demand billing is ideal for workloads with unpredictable traffic, as you only pay for the read/write operations you use.
Inserting Items into the Table
Once the DynamoDB table is created, the next step is to insert items into it. Terraform provides theaws_dynamodb_table_item resource for adding entries to your DynamoDB table. This resource requires the table name and hash key (which can be referenced from the table resource) along with the item data.
Below is an example configuration that includes both the table creation and the insertion of a single item into the table. Note the use of heredoc syntax (<<EOF ... EOF) for defining the item in valid JSON format, including the types for each attribute (e.g., “S” for string and “N” for number).
aws_dynamodb_table_item.car-items resource is being created. The process will output values similar to this:
This method is intended for managing a few items. For large-scale data management or bulk operations, consider alternative solutions or data migration strategies.