CodexBloom - Programming Q&A Platform

how to to Set Up an Azure SQL Database with Terraform Using Managed Identity for Authentication

👀 Views: 85 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-15
Terraform Azure SQL Database Managed Identity

I'm maintaining legacy code that I've searched everywhere and can't find a clear answer. I'm trying to provision an Azure SQL Database using Terraform and want to authenticate using a managed identity for my Azure Web App. However, I keep running into issues where the database want to be accessed with the managed identity, resulting in a `401 Unauthorized` behavior when attempting to connect. I've defined my resources as follows: ```hcl provider "azurerm" { features {} } resource "azurerm_resource_group" "example" { name = "example-resources" location = "East US" } resource "azurerm_sql_server" "example" { name = "example-sqlserver" resource_group_name = azurerm_resource_group.example.name location = azurerm_resource_group.example.location version = "12.0" administrator_login = "sqladmin" administrator_login_password = "P@ssword123!" } resource "azurerm_sql_database" "example" { name = "exampledb" resource_group_name = azurerm_resource_group.example.name location = azurerm_resource_group.example.location server_name = azurerm_sql_server.example.name requested_service_objective_name = "S0" } resource "azurerm_user_assigned_identity" "example" { name = "example-identity" resource_group_name = azurerm_resource_group.example.name location = azurerm_resource_group.example.location } resource "azurerm_web_app" "example" { name = "example-webapp" resource_group_name = azurerm_resource_group.example.name location = azurerm_resource_group.example.location server_farm_id = azurerm_app_service_plan.example.id identity { type = "UserAssigned" identity_ids = [azurerm_user_assigned_identity.example.id] } } resource "azurerm_sql_active_directory_administrator" "example" { server_id = azurerm_sql_server.example.id login = "example-identity" tenant_id = "<your-tenant-id>" } ``` I've also confirmed that the identity has been granted the necessary permissions to access the SQL Database. When I try to connect from my Web App, I use the following connection string: ```json "Server=tcp:example-sqlserver.database.windows.net;Authentication=Active Directory Managed Identity;Database=exampledb;" ``` Although the identity should have access, I'm still working with authorization issues. I've tried redeploying the resources and checking the permissions for the managed identity in SQL Server, but nothing seems to work. Any insights into what might be misconfigured or what additional steps I need to take would be greatly appreciated! For context: I'm using Terraform on Windows.