less than 1 minute read

This is how I provision DynamoDB with terraform

# dynamodb: jobs
resource "aws_dynamodb_table" "jobs_table" {
  name           = "${var.component}-jobs-${var.env}"
  billing_mode   = "PROVISIONED"
  read_capacity  = 5
  write_capacity = 5
  hash_key       = "companyId"
  range_key      = "jobNo"

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

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

  tags = {
    Name        = var.component
    Environment = var.env
  }
}

# policy for lambda to access dynamodb
data "aws_iam_policy_document" "iam_lambda_dynamodb_policy_document" {
  statement {
    effect = "Allow"
    actions = [
      "dynamodb:PutItem",
      "dynamodb:DeleteItem",
      "dynamodb:UpdateItem",
      "dynamodb:Get*",
      "dynamodb:Query",
      "dynamodb:DescribeTable"
    ]
    resources = [
      "arn:aws:dynamodb:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:table/${aws_dynamodb_table.jobs_table.name}",
      "arn:aws:dynamodb:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:table/${aws_dynamodb_table.users_table.name}"
    ]
  }
}

resource "aws_iam_policy" "iam_lambda_dynamodb_policy" {
  name   = "${var.component}_${var.env}_iam_lambda_dynamodb_policy"
  policy = data.aws_iam_policy_document.iam_lambda_dynamodb_policy_document.json
}

resource "aws_iam_role_policy_attachment" "lambda_dynamodb_policy_attachment" {
  role       = aws_iam_role.iam_lambda_role.name
  policy_arn = aws_iam_policy.iam_lambda_dynamodb_policy.arn
}

Comments