Monday 16 May 2022

Managing AWS DynamoDB using Terraform



Provisioning a new DynamoDB table


resource "aws_dynamodb_table" "mobile_phones" {
    name = "mobile_phones"
    hash_key = "IMEI"
    billing_mode = "PAY_PER_REQUEST"
    attribute = {
        name = "IMEI"
        type = "N"
    }
}

hash_key is table's primary key.
type = "N" means that data type is Number; "S" would mean that data type is String.
 
If we want to define more attributes, we'll add more attribute blocks e.g.
 
attribute {
    name = "Model"
    type = "S"
}

Adding new items to table

Item value needs to be in JSON format and we need to specify data type (S for string and N for number) and value.

resource "aws_dynamodb_table_item" {
    table_name = aws_dynamodb_table. mobile_phones.name
    hash_key = aws_dynamodb_table. mobile_phones.hash_key
    item = <<EOF
    {
        "Manufacturer": {"S" : "Samsung"},
        "Model": {"S": "S80"},
        "Year": {"N": 2017},
        "IMEI": {"N": 45243582345234632048432},
    }
    EOF
}

terraform apply inserts this item into the table. 

This approach is not used for inserting and managing large amounts of data.

No comments: