Integrate Azure Database for MySQL with Service Connector
บทความ
This page shows supported authentication methods and clients, and shows sample code you can use to connect Azure Database for MySQL - Flexible Server to other cloud services using Service Connector. This page also shows default environment variable names and values (or Spring Boot configuration) you get when you create the service connection.
Important
Azure Database for MySQL single server is on the retirement path. We strongly recommend that you upgrade to Azure Database for MySQL flexible server. For more information about migrating to Azure Database for MySQL flexible server, see What's happening to Azure Database for MySQL Single Server?
Supported compute services
Service Connector can be used to connect the following compute services to Azure Database for MySQL:
Azure App Service
Azure Container Apps
Azure Functions
Azure Kubernetes Service (AKS)
Azure Spring Apps
Supported authentication types and client types
The table below shows which combinations of authentication methods and clients are supported for connecting your compute service to Azure Database for MySQL using Service Connector. A “Yes” indicates that the combination is supported, while a “No” indicates that it is not supported.
Client type
System-assigned managed identity
User-assigned managed identity
Secret/connection string
Service principal
.NET
Yes
Yes
Yes
Yes
Go (go-sql-driver for mysql)
Yes
Yes
Yes
Yes
Java (JDBC)
Yes
Yes
Yes
Yes
Java - Spring Boot (JDBC)
Yes
Yes
Yes
Yes
Node.js (mysql)
Yes
Yes
Yes
Yes
Python (mysql-connector-python)
Yes
Yes
Yes
Yes
Python-Django
Yes
Yes
Yes
Yes
PHP (MySQLi)
Yes
Yes
Yes
Yes
Ruby (mysql2)
Yes
Yes
Yes
Yes
None
Yes
Yes
Yes
Yes
This table indicates that all combinations of client types and authentication methods in the table are supported. All client types can use any of the authentication methods to connect to Azure Database for MySQL using Service Connector.
Note
System-assigned managed identity, User-assigned managed identity and Service principal are only supported on Azure CLI.
Default environment variable names or application properties and sample code
Reference the connection details and sample code in following tables, according to your connection's authentication type and client type, to connect compute services to Azure Database for MySQL. For more information about naming conventions, check the Service Connector internals article.
For .NET, there's not a plugin or library to support passwordless connections. You can get an access token for the managed identity or service principal using client library like Azure.Identity. Then you can use the access token as the password to connect to the database. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
using Azure.Core;
using Azure.Identity;
using MySqlConnector;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned managed identity.
// var credential = new DefaultAzureCredential();
// For user-assigned managed identity.
// var credential = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTID");
// });
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_MYSQL_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTSECRET");
// var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
var tokenRequestContext = new TokenRequestContext(
new[] { "https://ossrdbms-aad.database.windows.net/.default" });
AccessToken accessToken = await credential.GetTokenAsync(tokenRequestContext);
// Open a connection to the MySQL server using the access token.
string connectionString =
$"{Environment.GetEnvironmentVariable("AZURE_MYSQL_CONNECTIONSTRING")};Password={accessToken.Token}";
using var connection = new MySqlConnection(connectionString);
Console.WriteLine("Opening connection using access token...");
await connection.OpenAsync();
// do something
Add the following dependencies in your pom.xml file:
For a Spring application, if you create a connection with option --client-type springboot, Service Connector sets the properties spring.datasource.azure.passwordless-enabled, spring.datasource.url, and spring.datasource.username to Azure Spring Apps.
Authenticate with access token get via azure-identity library and get connection information from the environment variable added by Service Connector. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
import mysql.connector
import os
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned managed identity.
# cred = ManagedIdentityCredential()
# For user-assigned managed identity.
# managed_identity_client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal
# tenant_id = os.getenv('AZURE_MYSQL_TENANTID')
# client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# client_secret = os.getenv('AZURE_MYSQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# acquire token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
# open connect to Azure MySQL with the access token.
host = os.getenv('AZURE_MYSQL_HOST')
database = os.getenv('AZURE_MYSQL_NAME')
user = os.getenv('AZURE_MYSQL_USER')
password = accessToken.token
cnx = mysql.connector.connect(user=user,
password=password,
host=host,
database=database)
cnx.close()
Install dependencies.
pip install azure-identity
Get access token via azure-identity library with the environment variables added by Service Connector. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
import os
# Uncomment the following lines corresponding to the authentication type you want to use.
# system-assigned managed identity
# cred = ManagedIdentityCredential()
# user-assigned managed identity
# managed_identity_client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# service principal
# tenant_id = os.getenv('AZURE_MYSQL_TENANTID')
# client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# client_secret = os.getenv('AZURE_MYSQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# acquire token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
In setting file, get Azure MySQL database information from environment variables added by Service Connector service. Use accessToken acquired in previous step to access the database.
# in your setting file, eg. settings.py
host = os.getenv('AZURE_MYSQL_HOST')
database = os.getenv('AZURE_MYSQL_NAME')
user = os.getenv('AZURE_MYSQL_USER')
password = accessToken.token # this is accessToken acquired from above step.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host
}
}
Install dependencies.
go get "github.com/go-sql-driver/mysql"
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
In code, get access token via azidentity, then connect to Azure MySQL with the token. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
import (
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/go-sql-driver/mysql"
)
func main() {
// Uncomment the following lines corresponding to the authentication type you want to use.
// for system-assigned managed identity
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// for user-assigned managed identity
// clientid := os.Getenv("AZURE_MYSQL_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// for service principal
// clientid := os.Getenv("AZURE_MYSQL_CLIENTID")
// tenantid := os.Getenv("AZURE_MYSQL_TENANTID")
// clientsecret := os.Getenv("AZURE_MYSQL_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
if err != nil {
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string("https://ossrdbms-aad.database.windows.net/.default"),
})
connectionString := os.Getenv("AZURE_MYSQL_CONNECTIONSTRING") + ";Password=" + token.Token
db, err := sql.Open("mysql", connectionString)
}
Get access token using @azure/identity and Azure MySQL database information from environment variables added by Service Connector service. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const mysql = require('mysql2');
// Uncomment the following lines corresponding to the authentication type you want to use.
// for system-assigned managed identity
// const credential = new DefaultAzureCredential();
// for user-assigned managed identity
// const clientId = process.env.AZURE_MYSQL_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// for service principal
// const tenantId = process.env.AZURE_MYSQL_TENANTID;
// const clientId = process.env.AZURE_MYSQL_CLIENTID;
// const clientSecret = process.env.AZURE_MYSQL_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// acquire token
var accessToken = await credential.getToken('https://ossrdbms-aad.database.windows.net/.default');
const connection = mysql.createConnection({
host: process.env.AZURE_MYSQL_HOST,
user: process.env.AZURE_MYSQL_USER,
password: accessToken.token,
database: process.env.AZURE_MYSQL_DATABASE,
port: process.env.AZURE_MYSQL_PORT,
ssl: process.env.AZURE_MYSQL_SSL
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL database: ' + err.stack);
return;
}
console.log('Connected to MySQL database');
});
For other languages, use the connection string and username that Service Connector sets to the environment variables to connect the database. For environment variable details, see Integrate Azure Database for MySQL with Service Connector.
For other languages, use the connection string and username that Service Connector sets to the environment variables to connect the database. For environment variable details, see Integrate Azure Database for MySQL with Service Connector.
For other languages, use the connection properties that Service Connector sets to the environment variables to connect the database. For environment variable details, see Integrate Azure Database for MySQL with Service Connector.
For .NET, there's not a plugin or library to support passwordless connections. You can get an access token for the managed identity or service principal using client library like Azure.Identity. Then you can use the access token as the password to connect to the database. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
using Azure.Core;
using Azure.Identity;
using MySqlConnector;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned managed identity.
// var credential = new DefaultAzureCredential();
// For user-assigned managed identity.
// var credential = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTID");
// });
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_MYSQL_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTSECRET");
// var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
var tokenRequestContext = new TokenRequestContext(
new[] { "https://ossrdbms-aad.database.windows.net/.default" });
AccessToken accessToken = await credential.GetTokenAsync(tokenRequestContext);
// Open a connection to the MySQL server using the access token.
string connectionString =
$"{Environment.GetEnvironmentVariable("AZURE_MYSQL_CONNECTIONSTRING")};Password={accessToken.Token}";
using var connection = new MySqlConnection(connectionString);
Console.WriteLine("Opening connection using access token...");
await connection.OpenAsync();
// do something
Add the following dependencies in your pom.xml file:
For a Spring application, if you create a connection with option --client-type springboot, Service Connector sets the properties spring.datasource.azure.passwordless-enabled, spring.datasource.url, and spring.datasource.username to Azure Spring Apps.
Authenticate with access token get via azure-identity library and get connection information from the environment variable added by Service Connector. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
import mysql.connector
import os
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned managed identity.
# cred = ManagedIdentityCredential()
# For user-assigned managed identity.
# managed_identity_client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal
# tenant_id = os.getenv('AZURE_MYSQL_TENANTID')
# client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# client_secret = os.getenv('AZURE_MYSQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# acquire token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
# open connect to Azure MySQL with the access token.
host = os.getenv('AZURE_MYSQL_HOST')
database = os.getenv('AZURE_MYSQL_NAME')
user = os.getenv('AZURE_MYSQL_USER')
password = accessToken.token
cnx = mysql.connector.connect(user=user,
password=password,
host=host,
database=database)
cnx.close()
Install dependencies.
pip install azure-identity
Get access token via azure-identity library with the environment variables added by Service Connector. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
import os
# Uncomment the following lines corresponding to the authentication type you want to use.
# system-assigned managed identity
# cred = ManagedIdentityCredential()
# user-assigned managed identity
# managed_identity_client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# service principal
# tenant_id = os.getenv('AZURE_MYSQL_TENANTID')
# client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# client_secret = os.getenv('AZURE_MYSQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# acquire token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
In setting file, get Azure MySQL database information from environment variables added by Service Connector service. Use accessToken acquired in previous step to access the database.
# in your setting file, eg. settings.py
host = os.getenv('AZURE_MYSQL_HOST')
database = os.getenv('AZURE_MYSQL_NAME')
user = os.getenv('AZURE_MYSQL_USER')
password = accessToken.token # this is accessToken acquired from above step.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host
}
}
Install dependencies.
go get "github.com/go-sql-driver/mysql"
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
In code, get access token via azidentity, then connect to Azure MySQL with the token. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
import (
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/go-sql-driver/mysql"
)
func main() {
// Uncomment the following lines corresponding to the authentication type you want to use.
// for system-assigned managed identity
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// for user-assigned managed identity
// clientid := os.Getenv("AZURE_MYSQL_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// for service principal
// clientid := os.Getenv("AZURE_MYSQL_CLIENTID")
// tenantid := os.Getenv("AZURE_MYSQL_TENANTID")
// clientsecret := os.Getenv("AZURE_MYSQL_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
if err != nil {
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string("https://ossrdbms-aad.database.windows.net/.default"),
})
connectionString := os.Getenv("AZURE_MYSQL_CONNECTIONSTRING") + ";Password=" + token.Token
db, err := sql.Open("mysql", connectionString)
}
Get access token using @azure/identity and Azure MySQL database information from environment variables added by Service Connector service. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const mysql = require('mysql2');
// Uncomment the following lines corresponding to the authentication type you want to use.
// for system-assigned managed identity
// const credential = new DefaultAzureCredential();
// for user-assigned managed identity
// const clientId = process.env.AZURE_MYSQL_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// for service principal
// const tenantId = process.env.AZURE_MYSQL_TENANTID;
// const clientId = process.env.AZURE_MYSQL_CLIENTID;
// const clientSecret = process.env.AZURE_MYSQL_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// acquire token
var accessToken = await credential.getToken('https://ossrdbms-aad.database.windows.net/.default');
const connection = mysql.createConnection({
host: process.env.AZURE_MYSQL_HOST,
user: process.env.AZURE_MYSQL_USER,
password: accessToken.token,
database: process.env.AZURE_MYSQL_DATABASE,
port: process.env.AZURE_MYSQL_PORT,
ssl: process.env.AZURE_MYSQL_SSL
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL database: ' + err.stack);
return;
}
console.log('Connected to MySQL database');
});
For other languages, use the connection string and username that Service Connector sets to the environment variables to connect the database. For environment variable details, see Integrate Azure Database for MySQL with Service Connector.
For other languages, use the connection string and username that Service Connector sets to the environment variables to connect the database. For environment variable details, see Integrate Azure Database for MySQL with Service Connector.
For other languages, use the connection properties that Service Connector sets to the environment variables to connect the database. For environment variable details, see Integrate Azure Database for MySQL with Service Connector.
Microsoft recommends that you use the most secure authentication flow available. The authentication flow described in this procedure requires a very high degree of trust in the application, and carries risks that are not present in other flows. You should only use this flow when other more secure flows, such as managed identities, aren't viable.
After created a springboot client type connection, Service Connector service will automatically add properties spring.datasource.url, spring.datasource.username, spring.datasource.password. So Spring boot application could add beans automatically.
In code, get MySQL connection string from environment variables added by Service Connector service. To establish encrypted connection to MySQL server over SSL, refer to these steps.
using System;
using System.Data;
using MySql.Data.MySqlClient;
string connectionString = Environment.GetEnvironmentVariable("AZURE_MYSQL_CONNECTIONSTRING");
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
}
In code, get MySQL connection string from environment variables added by Service Connector service. To establish encrypted connection to MySQL server over SSL, refer to these steps.
In code, get MySQL connection information from environment variables added by Service Connector service. To establish encrypted connection to MySQL server over SSL, refer to these steps.
In setting file, get MySQL database information from environment variables added by Service Connector service. To establish encrypted connection to MySQL server over SSL, refer to these steps.
In code, get MySQL connection string from environment variables added by Service Connector service. To establish encrypted connection to MySQL server over SSL, refer to these steps.
In code, get MySQL connection information from environment variables added by Service Connector service. To establish encrypted connection to MySQL server over SSL, refer to these steps.
const mysql = require('mysql2')
const connection = mysql.createConnection({
host: process.env.AZURE_MYSQL_HOST,
user: process.env.AZURE_MYSQL_USER,
password: process.env.AZURE_MYSQL_PASSWORD,
database: process.env.AZURE_MYSQL_DATABASE,
port: Number(process.env.AZURE_MYSQL_PORT) ,
// ssl: process.env.AZURE_MYSQL_SSL
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL database: ' + err.stack);
return;
}
console.log('Connected to MySQL database.');
});
Install dependencies. Follow the guide to install MySQLi.
In code, get MySQL connection information from environment variables added by Service Connector service. To establish encrypted connection to MySQL server over SSL, refer to these steps.
In code, get MySQL connection information from environment variables added by Service Connector service. To establish encrypted connection to MySQL server over SSL, refer to these steps.
For other languages, use the connection properties that Service Connector sets to the environment variables to connect the database. For environment variable details, see Integrate Azure Database for MySQL with Service Connector.
For .NET, there's not a plugin or library to support passwordless connections. You can get an access token for the managed identity or service principal using client library like Azure.Identity. Then you can use the access token as the password to connect to the database. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
using Azure.Core;
using Azure.Identity;
using MySqlConnector;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned managed identity.
// var credential = new DefaultAzureCredential();
// For user-assigned managed identity.
// var credential = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTID");
// });
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_MYSQL_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTSECRET");
// var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
var tokenRequestContext = new TokenRequestContext(
new[] { "https://ossrdbms-aad.database.windows.net/.default" });
AccessToken accessToken = await credential.GetTokenAsync(tokenRequestContext);
// Open a connection to the MySQL server using the access token.
string connectionString =
$"{Environment.GetEnvironmentVariable("AZURE_MYSQL_CONNECTIONSTRING")};Password={accessToken.Token}";
using var connection = new MySqlConnection(connectionString);
Console.WriteLine("Opening connection using access token...");
await connection.OpenAsync();
// do something
Add the following dependencies in your pom.xml file:
For a Spring application, if you create a connection with option --client-type springboot, Service Connector sets the properties spring.datasource.azure.passwordless-enabled, spring.datasource.url, and spring.datasource.username to Azure Spring Apps.
Authenticate with access token get via azure-identity library and get connection information from the environment variable added by Service Connector. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
import mysql.connector
import os
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned managed identity.
# cred = ManagedIdentityCredential()
# For user-assigned managed identity.
# managed_identity_client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal
# tenant_id = os.getenv('AZURE_MYSQL_TENANTID')
# client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# client_secret = os.getenv('AZURE_MYSQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# acquire token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
# open connect to Azure MySQL with the access token.
host = os.getenv('AZURE_MYSQL_HOST')
database = os.getenv('AZURE_MYSQL_NAME')
user = os.getenv('AZURE_MYSQL_USER')
password = accessToken.token
cnx = mysql.connector.connect(user=user,
password=password,
host=host,
database=database)
cnx.close()
Install dependencies.
pip install azure-identity
Get access token via azure-identity library with the environment variables added by Service Connector. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
import os
# Uncomment the following lines corresponding to the authentication type you want to use.
# system-assigned managed identity
# cred = ManagedIdentityCredential()
# user-assigned managed identity
# managed_identity_client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# service principal
# tenant_id = os.getenv('AZURE_MYSQL_TENANTID')
# client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# client_secret = os.getenv('AZURE_MYSQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# acquire token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
In setting file, get Azure MySQL database information from environment variables added by Service Connector service. Use accessToken acquired in previous step to access the database.
# in your setting file, eg. settings.py
host = os.getenv('AZURE_MYSQL_HOST')
database = os.getenv('AZURE_MYSQL_NAME')
user = os.getenv('AZURE_MYSQL_USER')
password = accessToken.token # this is accessToken acquired from above step.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host
}
}
Install dependencies.
go get "github.com/go-sql-driver/mysql"
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
In code, get access token via azidentity, then connect to Azure MySQL with the token. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
import (
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/go-sql-driver/mysql"
)
func main() {
// Uncomment the following lines corresponding to the authentication type you want to use.
// for system-assigned managed identity
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// for user-assigned managed identity
// clientid := os.Getenv("AZURE_MYSQL_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// for service principal
// clientid := os.Getenv("AZURE_MYSQL_CLIENTID")
// tenantid := os.Getenv("AZURE_MYSQL_TENANTID")
// clientsecret := os.Getenv("AZURE_MYSQL_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
if err != nil {
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string("https://ossrdbms-aad.database.windows.net/.default"),
})
connectionString := os.Getenv("AZURE_MYSQL_CONNECTIONSTRING") + ";Password=" + token.Token
db, err := sql.Open("mysql", connectionString)
}
Get access token using @azure/identity and Azure MySQL database information from environment variables added by Service Connector service. When using the code below, uncomment the part of the code snippet for the authentication type you want to use.
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const mysql = require('mysql2');
// Uncomment the following lines corresponding to the authentication type you want to use.
// for system-assigned managed identity
// const credential = new DefaultAzureCredential();
// for user-assigned managed identity
// const clientId = process.env.AZURE_MYSQL_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// for service principal
// const tenantId = process.env.AZURE_MYSQL_TENANTID;
// const clientId = process.env.AZURE_MYSQL_CLIENTID;
// const clientSecret = process.env.AZURE_MYSQL_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// acquire token
var accessToken = await credential.getToken('https://ossrdbms-aad.database.windows.net/.default');
const connection = mysql.createConnection({
host: process.env.AZURE_MYSQL_HOST,
user: process.env.AZURE_MYSQL_USER,
password: accessToken.token,
database: process.env.AZURE_MYSQL_DATABASE,
port: process.env.AZURE_MYSQL_PORT,
ssl: process.env.AZURE_MYSQL_SSL
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL database: ' + err.stack);
return;
}
console.log('Connected to MySQL database');
});
For other languages, use the connection string and username that Service Connector sets to the environment variables to connect the database. For environment variable details, see Integrate Azure Database for MySQL with Service Connector.
For other languages, use the connection string and username that Service Connector sets to the environment variables to connect the database. For environment variable details, see Integrate Azure Database for MySQL with Service Connector.
For other languages, use the connection properties that Service Connector sets to the environment variables to connect the database. For environment variable details, see Integrate Azure Database for MySQL with Service Connector.