0

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.

4
  • Have you checked this resource provider called "azurerm_sql_active_directory_administrator". @Neutrino Commented Mar 13, 2024 at 6:21
  • Yes I have. That resource supports setting the AD administrator for the SQL server, which in my Terraform script I'm doing by setting the AD admin on the SLQ server directly. But what I'm trying to do is add a database user based on an AD user to the database (not the server). Does this resource help with that, if so how? Commented Mar 13, 2024 at 9:28
  • Can you check this SO if this works for you? @Neutrino Commented Mar 13, 2024 at 9:48
  • 1
    I saw that already. That's not using Terraform, that's just running a script. Commented Mar 13, 2024 at 10:38

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.