Databricks Python connect to Azure SQL server using managed identity

CzarR 296 Reputation points
2023-04-04T20:15:43.6666667+00:00

HI, I have a task to connect to a Azure SQL server database using python using managed identity. I was given a system assigned objectID for the VM, a secretkey, scope and a managed identity account name. 1.) objectID = "auf30c96-65n7-4f70-a346-765ec0587432" 2.) secretkey 3.) scope 4.) managed identity account name. I was told using managed identity authentication I need to connect to sql server. So far I tried this with the following error"OperationalError: ('08S01', '[08S01] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x2746 (10054) (SQLDriverConnect)')". Any help is appreciated as I am new to this authentication and Azure in general. Thanks in advance. I was instructed that I should be able to build the connection string from the secretkey and pass that into pyodbc.connect. But unable to accomplish that.

import structimport pyodbcscopename = "az-keyvault"secretkey = "az-db-conn-odbc"credhwm = dbutils.secrets.get(scope=scopename, key=secretkey)SQL_COPT_SS_ACCESS_TOKEN = 1256exptoken = b'';for i in bytes(db_token, "UTF-8"):    exptoken += bytes({i});    exptoken += bytes(1);tokenstruct = struct.pack("=i", len(exptoken)) + exptoken;conn = pyodbc.connect(credhwm, attrs_before = { SQL_COPT_SS_ACCESS_TOKEN:tokenstruct })with conn.cursor() as cursor:    cursor.execute("SELECT getdate()")    row = cursor.fetchone()    print(row[0])
Azure Databricks
Azure Databricks
An Apache Spark-based analytics platform optimized for Azure.
2,261 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.