How do I create an Azue SQL database user from a managed identity using Terraform?

83 Views Asked by At

Using the following code I can create an SQL server, which has a security group set for the AD administrator, and I can then add the system assigned identity of a web service (or anything else) to the security group to enable that service to access the database.


variable "app_service" { }

data "azuread_client_config" "current" {}

# Create a security group

resource "azuread_group" "grp_1" {
  display_name     = "appname-sqladmin"
  owners           = [data.azuread_client_config.current.object_id]
  security_enabled = true
}

# Create SQL server

resource "azurerm_mssql_server" "sqlsvr" {
  name                         = "appname-sqlsvr"
  resource_group_name          = "resource_group_name"
  location                     = "resource_group_location"
  version                      = "12.0"

  azuread_administrator {
    login_username = azuread_group.grp_1.display_name
    object_id = azuread_group.grp_1.id
    azuread_authentication_only = true
  }
}

# Create SQL database

resource "azurerm_mssql_database" "sqldb" {
  name                          = "appname-sqldb"
  server_id                     = azurerm_mssql_server.sqlsvr.id
  max_size_gb                   = 1
  sku_name                      = "Basic"
  storage_account_type          = "Local"
}

resource "azuread_group_member" "grp_mbr_1" {
  group_object_id = azuread_group.grp_1.id
  member_object_id = var.app_service.identity.0.principal_id
}

That works, but it's not ideal because the service then has admin access to the entire SQL server instead of access to just the database.

So using Terraform is there any way to a create a database user that maps to an AD identity and assign database roles to it?

The Terraform runs on my Windows desktop and an Azure Linux build agent, so I don't really want to be running cli scripts inside it and having to rely on different cli tools being available in different environments.

0

There are 0 best solutions below