Create AWS DynamoDB Tables with PowerShell

You can use the AWS PowerShell module to create DynamoDB tables. If you need help setting up the AWS PowerShell module, start by watching this video.

There’s a helper function called New-DDBSchema, which creates a .NET TableSchema object. Start by assigning the output from this command to a variable; you can name the variable whatever you’d like, but I have chosen $schema.

$schema = New-DDBSchema

Adding Your Attribute Defintions

Next, you need to add your schema’s attribute definitions. You can define attributes as string (S), binary (B), or number (N) values. The TableSchema object that you just created has a property named AttributeSchema, which is a collection of AttributeDefinition objects.

In this example, we’ll create two attribute definitions and call them: LastName, and FirstName. Both attributes will be defined as string (S) attributes, as opposed to binary (B) or number (N).

$schema.AttributeSchema.Add([Amazon.DynamoDBv2.Model.AttributeDefinition]::new('LastName', [Amazon.DynamoDBv2.ScalarAttributeType]::S))
$schema.AttributeSchema.Add([Amazon.DynamoDBv2.Model.AttributeDefinition]::new('FirstName', [Amazon.DynamoDBv2.ScalarAttributeType]::S))

Adding Your HASH and RANGE keys

Now that you’ve declared your attribute definitions, you can use them as your HASH (PARTITION) and RANGE (SORT) keys. In reality, it doesn’t matter whether you add the attribute definitions first or not, because the object model doesn’t enforce any ordering. However, it’s good to remember that you can only use attributes that have explicit attribute definitions as HASH and RANGE keys. All that matters is that you construct the objects correctly, before sending them off to the AWS DynamoDB CreateTable API.

The TableSchema object has another property called KeySchema, which is a collection of KeySchemaElement objects. You’ll need to use the KeyType class as the second parameter to the constructor of the KeySchemaElement objects.

$schema.KeySchema.Add([Amazon.DynamoDBv2.Model.KeySchemaElement]::new('LastName', [Amazon.DynamoDBv2.KeyType]::new('HASH')))
$schema.KeySchema.Add([Amazon.DynamoDBv2.Model.KeySchemaElement]::new('FirstName', [Amazon.DynamoDBv2.KeyType]::new('RANGE')))

Create Your DynamoDB Table

You only need to worry about a few more parameters to create a DynamoDB table. We’ll use PowerShell Splatting syntax to declare the parameters and pass them into the New-DDBTable command. Notice that the TableSchema object you just created in the earlier sections will be passed into the -Schema parameter on the New-DDBTable command.

$DDBTable = @{
  TableName = 'trevor'
  Schema = $schema
  ReadCapacity = 1
  WriteCapacity = 1
  Region = 'us-west-2'
New-DDBTable @DDBTable