Terraform入門(AWS DynamoDB構築)

はじめに

DynamoDBは他のサービスとの連携がほとんどないのでシンプル。

DynamoDB Streamsの設定も2つのオプションを設定するだけで可能。

設定ファイル

一旦設定ファイルの全体を公開。

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 2.70"
    }
  }
}

provider "aws" {
  profile = "default"
  region  = "ap-northeast-1"
}

# DynamoDB
resource "aws_dynamodb_table" "sample" {
  name           = "Sample"
  billing_mode   = "PROVISIONED"
  read_capacity  = 1
  write_capacity = 1
  hash_key       = "user_id"

  stream_enabled = true
  stream_view_type = "NEW_AND_OLD_IMAGES"

  attribute {
    name = "user_id"
    type = "S"
  }

  tags = {
    Name        = "Sample"
    Environment = "dev"
  }
}

DynamoDB

TerraformのDynamoDBのドキュメントを見ながら構築しましょう。

resource "aws_dynamodb_table" "sample" {
  name           = "Sample"
  billing_mode   = "PROVISIONED"
  read_capacity  = 1
  write_capacity = 1
  hash_key       = "user_id"

  stream_enabled = true
  stream_view_type = "NEW_AND_OLD_IMAGES"

  attribute {
    name = "user_id"
    type = "S"
  }

  tags = {
    Name        = "Sample"
    Environment = "dev"
  }
}

resource名

aws_dynamodb_table

必須項目

  • name
  • hash_key
  • attribute ※hash_key/range_keyに指定されたattributeは必須
  • write_capacity ※billing_mode = “PROVISIONED”の場合必須
  • read_capacity※billing_mode = “PROVISIONED”の場合必須

DynamoDB Stream

  • stream_enabled
  • stream_view_type

Global Secondary Index

  global_secondary_index {
    name               = "client_public_key_index"
    hash_key           = "client_public_key"
    write_capacity     = 1
    read_capacity      = 1
    projection_type    = "INCLUDE"
    non_key_attributes = ["local_ip"]
  }

必須項目

  • name
  • hash_key
  • projection_type