Azure Azure - Terraform templates

MS SQL Database

Last updated: November 28, 2024
You can create the a new MSSQL Database using the snippet below:

resource "azurerm_mssql_database" "db" {
  name      = "${var.environment_prefix}-${var.solution_prefix}${var.customer_prefix}"
  server_id = azurerm_mssql_server.server.id
  
  collation      = "SQL_Latin1_General_CP1_CI_AS"
  license_type   = "LicenseIncluded"
  max_size_gb    = 1
  read_scale     = false
  sku_name       = "S0"
  zone_redundant = false # set to true for business critical apps. Settable for Premium and Business Critical databases

  tags = var.tags
}

Note: You need a MS SQL Server before you can create a MS SQL Database. You can find the details about creating MS SQL Server on this link

It is recommended that you turn on prevent_destroy flag in order to protect your DB from accidental deletion. You can do this by adding the lifecycle block to the code above.

resource "azurerm_mssql_database" "db" {
  name      = "${var.environment_prefix}-${var.solution_prefix}${var.customer_prefix}"
  server_id = azurerm_mssql_server.server.id
  
  collation      = "SQL_Latin1_General_CP1_CI_AS"
  license_type   = "LicenseIncluded"
  max_size_gb    = 1
  read_scale     = false
  sku_name       = "S0"
  zone_redundant = false # set to true for business critical apps. Settable for Premium and Business Critical databases

  tags = var.tags

  # prevent the possibility of accidental data loss
  # Read more on: https://developer.hashicorp.com/terraform/tutorials/state/resource-lifecycle#prevent-resource-deletion
  lifecycle {
    prevent_destroy = true
  }
}

Further reading