Is there a way to use Azure managed identities with Linux VMs to access Azure SQL DB? All I could find is this document https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/tutorial-windows-vm-access-sql which specifically speaks to Windows VMs. Is there a documented step-by-step approach for a Linux machine?
2 Answers
SQL access using Managed Identity from Linux webapp is supported. The Use a Windows VM system-assigned managed identity to access Azure SQL tutorial is pretty much applicable to Linux, just dismiss the code sample and use something like this:
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://database.windows.net/");
using
var sqlConnection = new SqlConnection(configuration.GetConnectionString("Default")) {
AccessToken = accessToken
};
using
var sqlCommand = new SqlCommand("SELECT @@VERSION", sqlConnection);
await sqlConnection.OpenAsync();
var version = (string) await sqlCommand.ExecuteScalarAsync();
Full code available here, just replace the connection string with yours.
3 Comments
Nana
Thank you for the response Alfredo. Comparing your code to the Access data step for the Windows VM learn.microsoft.com/en-us/azure/active-directory/… where is the Azure SQL servername specified. Or is it not necessary in your code?
AlfredoRevilla-MSFT
@Nana it is. In my code all the connection string is retrieved from the configuration and set in the SqlConnection constructor:
new SqlConnection(configuration.GetConnectionString("Default")). Check the appsettings.json file for a "Default" named connection string.It seems the managed identity does not support for Linux VMs to access Azure SQL DB.
There is a similar issue here. And there is a workaround which uses the cross-platform .NET core libraries, you could refer to it.
3 Comments
Nana
Thank you for the response Pamela
AlfredoRevilla-MSFT
Hi Pamela. Please take a look at my answer.
unknown
@Alfredo-MSFTIdentity Maybe I misunderstand it because I cannot find the official doc about it. Thanks for your answer.