Azure Automation Account, Python 3 Runbook, SQL Server Token Authentication
Hi,
I am trying to use a Python 3 Runbook in a Azure Automation Account to connect to a Azure SQL Server using Token authentication.
Using a Python 3 Azure Runbook, I can connect to Azure SQL Server using SQL Authentication, no problem there.
Using Python 3 locally on my laptop, I can connect to Azure SQL Server using Token Authentication, no problem there either.
However when using that same code in a Azure Runbook, I'm faced with a few problems.
Firstly, when using the {ODBC Driver 17 for SQL Server}, I get the following error message:
[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
Secondly, if changing the driver to {SQL Server}, I am faced with a different problem:
[ODBC SQL Server Driver][SQL Server]Windows logins are not supported in this version of SQL Server
Thirdly, I have added "Integrated Security=False;" to the connection string, but now get this error:
[ODBC SQL Server Driver]Invalid connection string attribute.
My code is below...
#!/usr/bin/env python3
import adal
from msrestazure.azure_active_directory import AADTokenCredentials
import pyodbc
import struct
resource = "x"
tenant = "x"
authorityHostUrl = "https://login.microsoftonline.com"
clientId = "x"
clientSecret = "x"
authority_uri = authorityHostUrl + '/' + tenant
resource_uri = 'https://database.windows.net/'
context = adal.AuthenticationContext(authority_uri, api_version=None)
mgmt_token = context.acquire_token_with_client_credentials(resource_uri, clientId, clientSecret)
token = mgmt_token["accessToken"]
SQL_COPT_SS_ACCESS_TOKEN = 1256
driver = "{ODBC Driver 17 for SQL Server}"
server = "x.database.windows.net"
database = "x"
connString = "DRIVER=" + driver + ";SERVER=" + server + ";DATABASE=" + database +";Trusted_Connection=False;Encrypt=True;Integrated Security=False;"
tokenb = bytes(token, "UTF-8")
exptoken = b''
for i in tokenb:
exptoken += bytes({i})
exptoken += bytes(1)
tokenstruct = struct.pack("=i", len(exptoken)) + exptoken
conn = pyodbc.connect(connString, attrs_before = {SQL_COPT_SS_ACCESS_TOKEN:tokenstruct})
cursor = conn.cursor()
cursor.execute("SELECT TOP (5) * FROM Reference")
row = cursor.fetchone()
for i in row:
print(i)