이 페이지에서는 지원되는 인증 방법과 클라이언트를 보여주며 서비스 커넥터를 사용하여 Azure Database for MySQL - 유연한 서버를 다른 클라우드 서비스에 연결하는 데 사용할 수 있는 샘플 코드를 보여줍니다. 이 페이지에서는 서비스 연결을 만들 때 가져오는 기본 환경 변수 이름과 값(또는 Spring Boot 구성)도 보여 줍니다.
Important
Azure Database for MySQL 단일 서버는 사용 중지를 향한 여정에 있습니다. Azure Database for MySQL 유연한 서버로 업그레이드하는 것이 좋습니다. Azure Database for MySQL - 유연한 서버로 마이그레이션하는 방법에 대한 자세한 내용은 Azure Database for MySQL 단일 서버에 대한 새로운 소식을 참조하세요.
지원되는 컴퓨팅 서비스
서비스 커넥터를 사용하여 Azure Database for MySQL에 다음 컴퓨팅 서비스를 연결할 수 있습니다.
- Azure App Service
- Azure Container Apps
- Azure 기능
- AKS(Azure Kubernetes Service)
- Azure Spring Apps
지원되는 인증 유형 및 클라이언트 유형
아래 표에서는 서비스 커넥터를 사용하여 컴퓨팅 서비스를 Azure Database for MySQL에 연결하는 데 지원되는 인증 방법과 클라이언트의 조합을 보여줍니다. 해당 조합이 지원되면 “예”, 지원되지 않으면 “아니요”입니다.
클라이언트 유형 |
시스템 할당 관리 ID |
사용자 할당 관리 ID |
비밀/연결 문자열 |
서비스 사용자 |
.NET |
예 |
예 |
예 |
예 |
Go(mysql용 go-sql-driver) |
예 |
예 |
예 |
예 |
Java(JDBC) |
예 |
예 |
예 |
예 |
Java - Spring Boot(JDBC) |
예 |
예 |
예 |
예 |
Node.js(mysql) |
예 |
예 |
예 |
예 |
Python(mysql-connector-python) |
예 |
예 |
예 |
예 |
Python-Django |
예 |
예 |
예 |
예 |
PHP(MySQLi) |
예 |
예 |
예 |
예 |
Ruby(mysql2) |
예 |
예 |
예 |
예 |
없음 |
예 |
예 |
예 |
예 |
이 표는 표에 있는 클라이언트 유형과 모든 인증 방법 조합이 지원됨을 나타냅니다. 모든 클라이언트 유형은 어떤 인증 방법을 택하더라도 서비스 커넥터를 사용하여 Azure Database for MySQL에 연결할 수 있습니다.
참고 항목
시스템이 할당한 관리 ID, 사용자가 할당한 관리 ID 및 서비스 주체는 Azure CLI에서만 지원됩니다.
기본 환경 변수 이름 또는 애플리케이션 속성 및 샘플 코드
연결의 인증 유형 및 클라이언트 유형에 따라 다음 표의 연결 세부 정보 및 샘플 코드를 참조하여 컴퓨팅 서비스를 Azure Database for MySQL에 연결합니다. 명명 규칙에 대한 자세한 내용은 서비스 커넥터 내부 문서를 참조하세요.
시스템이 할당한 관리 ID
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_CONNECTIONSTRING |
ADO.NET MySQL 연결 문자열 |
Server=<MySQL-DB-name>.mysql.database.azure.com;Database=<MySQL-DB-name>;Port=3306;User Id=<MySQL-DBusername>;SSL Mode=Required; |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_CONNECTIONSTRING |
JDBC MySQL 연결 문자열 |
jdbc:mysql://<MySQL-DB-name>.mysql.database.azure.com:3306/<MySQL-DB-name>?sslmode=required&user=<MySQL-DB-username> |
애플리케이션 속성 |
설명 |
예제 값 |
spring.datasource.azure.passwordless-enabled |
암호 없는 인증 사용 |
true |
spring.datasource.url |
Spring Boot JDBC 데이터베이스 URL |
jdbc:mysql://<MySQL-DB-name>.mysql.database.azure.com:3306/<MySQL-DB-name>?sslmode=required |
spring.datasource.username |
데이터베이스 사용자 이름 |
<MySQL-DB-username> |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_NAME |
데이터베이스 이름 |
MySQL-DB-name |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
데이터베이스 사용자 이름 |
<MySQL-DB-username>@<MySQL-DB-name> |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_NAME |
데이터베이스 이름 |
MySQL-DB-name |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
데이터베이스 사용자 이름 |
<MySQL-DB-username>@<MySQL-DB-name> |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_CONNECTIONSTRING |
Go-sql-driver 연결 문자열 |
<MySQL-DB-username>@tcp(<server-host>:<port>)/<MySQL-DB-name>?tls=true |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
데이터베이스 사용자 이름 |
MySQL-DB-username |
AZURE_MYSQL_DATABASE |
데이터베이스 이름 |
<database-name> |
AZURE_MYSQL_PORT |
포트 번호 |
3306 |
AZURE_MYSQL_SSL |
SSL 옵션 |
true |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_DBNAME |
데이터베이스 이름 |
<MySQL-DB-name> |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_PORT |
포트 번호 |
3306 |
AZURE_MYSQL_FLAG |
SSL 또는 기타 플래그 |
MySQL_CLIENT_SSL |
AZURE_MYSQL_USERNAME |
데이터베이스 사용자 이름 |
<MySQL-DB-username> |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_DATABASE |
데이터베이스 이름 |
<MySQL-DB-name> |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USERNAME |
데이터베이스 사용자 이름 |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_SSLMODE |
SSL 옵션 |
required |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USERNAME |
데이터베이스 사용자 이름 |
MySQL-DB-username |
AZURE_MYSQL_DATABASE |
데이터베이스 이름 |
<database-name> |
AZURE_MYSQL_PORT |
포트 번호 |
3306 |
AZURE_MYSQL_SSL |
SSL 옵션 |
true |
샘플 코드
아래 단계와 코드를 참조하여 시스템이 할당한 관리 ID로 Azure Database for MySQL에 연결합니다.
.NET의 경우 암호 없는 연결을 지원하는 플러그 인 또는 라이브러리가 없습니다.
Azure.Identity와 같은 클라이언트 라이브러리를 사용하여 관리 ID 또는 서비스 주체에 대한 액세스 토큰을 가져올 수 있습니다. 그런 다음 액세스 토큰을 암호로 사용하여 데이터베이스에 연결할 수 있습니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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
pom.xml 파일에서 다음 종속성을 추가합니다.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity-extensions</artifactId>
<version>1.2.0</version>
</dependency>
환경 변수에서 연결 문자열을 가져와서 플러그 인 이름을 추가하여 데이터베이스에 연결합니다.
String url = System.getenv("AZURE_MYSQL_CONNECTIONSTRING");
String pluginName = "com.azure.identity.extensions.jdbc.mysql.AzureMysqlAuthenticationPlugin";
Properties properties = new Properties();
properties.put("defaultAuthenticationPlugin", pluginName);
properties.put("authenticationPlugins", pluginName);
// Uncomment the following lines corresponding to the authentication type you want to use.
// for user-assigned managed identity
// String clientId = System.getenv('AZURE_MYSQL_CLIENTID')
// properties.put("azure.clientId", clientId);
// For service principal
// String tenantId = System.getenv('AZURE_MYSQL_TENANTID')
// String clientId = System.getenv('AZURE_MYSQL_CLIENTID')
// String clientSecret = System.getenv('AZURE_MYSQL_CLIENTSECRET')
// properties.put("azure.clientId", clientId);
// properties.put("azure.clientSecret", clientSecret);
// properties.put("azure.tenantId", tenantId);
Connection connection = DriverManager.getConnection(url, properties);
자세한 내용은 Azure Database for MySQL - 유연한 서버에서 Java 및 JDBC 사용을 참조하세요.
종속성 설치
pip install azure-identity
# install Connector/Python https://dev.mysql.com/doc/connector-python/en/connector-python-installation.html
pip install mysql-connector-python
azure-identity
라이브러리를 통해 액세스 토큰으로 인증하고 서비스 커넥터에서 추가한 환경 변수의 연결 정보를 가져옵니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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()
종속성을 설치합니다.
pip install azure-identity
서비스 커넥터에서 추가한 환경 변수를 사용하여 azure-identity
라이브러리를 통해 액세스 토큰을 가져옵니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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')
설정 파일의 서비스 커넥터 서비스에서 추가한 환경 변수에서 Azure MySQL 데이터베이스 정보를 가져옵니다. 이전 단계에서 얻은 accessToken
을 사용하여 데이터베이스에 액세스합니다.
# 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
}
}
종속성을 설치합니다.
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"
코드에서 azidentity
를 통해 액세스 토큰을 가져오고 해당 토큰으로 Azure MySQL에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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)
}
종속성 설치
npm install --save @azure/identity
npm install --save mysql2
@azure/identity
및 서비스 커넥터 서비스에서 추가한 환경 변수의 Azure MySQL 데이터베이스 정보를 사용하여 액세스 토큰을 가져옵니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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');
});
코드 샘플에 대한 자세한 내용은 관리 ID를 사용하여 비밀 없이 App Service에서 Azure 데이터베이스에 연결을 참조하세요.
사용자가 할당한 관리 ID
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<identity-client-ID> |
AZURE_MYSQL_CONNECTIONSTRING |
ADO.NET MySQL 연결 문자열 |
Server=<MySQL-DB-name>.mysql.database.azure.com;Database=<MySQL-DB-name>;Port=3306;User Id=<MySQL-DBusername>;SSL Mode=Required; |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<identity-client-ID> |
AZURE_MYSQL_CONNECTIONSTRING |
JDBC MySQL 연결 문자열 |
jdbc:mysql://<MySQL-DB-name>.mysql.database.azure.com:3306/<MySQL-DB-name>?sslmode=required&user=<MySQL-DB-username> |
애플리케이션 속성 |
설명 |
예제 값 |
spring.datasource.azure.passwordless-enabled |
암호 없는 인증 사용 |
true |
spring.cloud.azure.credential.client-id |
클라이언트 ID |
<identity-client-ID> |
spring.cloud.azure.credential.client-managed-identity-enabled |
클라이언트 관리 ID 사용 |
true |
spring.datasource.url |
데이터베이스 URL |
jdbc:mysql://<MySQL-DB-name>.mysql.database.azure.com:3306/<MySQL-DB-name>?sslmode=required |
spring.datasource.username |
데이터베이스 사용자 이름 |
username |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_NAME |
데이터베이스 이름 |
MySQL-DB-name |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
데이터베이스 사용자 이름 |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
identity-client-ID |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_NAME |
데이터베이스 이름 |
MySQL-DB-name |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
데이터베이스 사용자 이름 |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<identity-client-ID> |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<identity-client-ID> |
AZURE_MYSQL_CONNECTIONSTRING |
Go-sql-driver 연결 문자열 |
<MySQL-DB-username>@tcp(<server-host>:<port>)/<MySQL-DB-name>?tls=true |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
데이터베이스 사용자 이름 |
MySQL-DB-username |
AZURE_MYSQL_DATABASE |
데이터베이스 이름 |
<database-name> |
AZURE_MYSQL_PORT |
포트 번호 |
3306 |
AZURE_MYSQL_SSL |
SSL 옵션 |
true |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<identity-client-ID> |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_DBNAME |
데이터베이스 이름 |
<MySQL-DB-name> |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_PORT |
포트 번호 |
3306 |
AZURE_MYSQL_FLAG |
SSL 또는 기타 플래그 |
MySQL_CLIENT_SSL |
AZURE_MYSQL_USERNAME |
데이터베이스 사용자 이름 |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<identity-client-ID> |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_DATABASE |
데이터베이스 이름 |
<MySQL-DB-name> |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USERNAME |
데이터베이스 사용자 이름 |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_SSLMODE |
SSL 옵션 |
required |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<identity-client-ID> |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USERNAME |
데이터베이스 사용자 이름 |
MySQL-DB-username |
AZURE_MYSQL_DATABASE |
데이터베이스 이름 |
<database-name> |
AZURE_MYSQL_PORT |
포트 번호 |
3306 |
AZURE_MYSQL_SSL |
SSL 옵션 |
true |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<identity-client-ID> |
샘플 코드
아래 단계와 코드를 참조하여 사용자가 할당한 관리 ID로 Azure Database for MySQL에 연결합니다.
.NET의 경우 암호 없는 연결을 지원하는 플러그 인 또는 라이브러리가 없습니다.
Azure.Identity와 같은 클라이언트 라이브러리를 사용하여 관리 ID 또는 서비스 주체에 대한 액세스 토큰을 가져올 수 있습니다. 그런 다음 액세스 토큰을 암호로 사용하여 데이터베이스에 연결할 수 있습니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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
pom.xml 파일에서 다음 종속성을 추가합니다.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity-extensions</artifactId>
<version>1.2.0</version>
</dependency>
환경 변수에서 연결 문자열을 가져와서 플러그 인 이름을 추가하여 데이터베이스에 연결합니다.
String url = System.getenv("AZURE_MYSQL_CONNECTIONSTRING");
String pluginName = "com.azure.identity.extensions.jdbc.mysql.AzureMysqlAuthenticationPlugin";
Properties properties = new Properties();
properties.put("defaultAuthenticationPlugin", pluginName);
properties.put("authenticationPlugins", pluginName);
// Uncomment the following lines corresponding to the authentication type you want to use.
// for user-assigned managed identity
// String clientId = System.getenv('AZURE_MYSQL_CLIENTID')
// properties.put("azure.clientId", clientId);
// For service principal
// String tenantId = System.getenv('AZURE_MYSQL_TENANTID')
// String clientId = System.getenv('AZURE_MYSQL_CLIENTID')
// String clientSecret = System.getenv('AZURE_MYSQL_CLIENTSECRET')
// properties.put("azure.clientId", clientId);
// properties.put("azure.clientSecret", clientSecret);
// properties.put("azure.tenantId", tenantId);
Connection connection = DriverManager.getConnection(url, properties);
자세한 내용은 Azure Database for MySQL - 유연한 서버에서 Java 및 JDBC 사용을 참조하세요.
종속성 설치
pip install azure-identity
# install Connector/Python https://dev.mysql.com/doc/connector-python/en/connector-python-installation.html
pip install mysql-connector-python
azure-identity
라이브러리를 통해 액세스 토큰으로 인증하고 서비스 커넥터에서 추가한 환경 변수의 연결 정보를 가져옵니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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()
종속성을 설치합니다.
pip install azure-identity
서비스 커넥터에서 추가한 환경 변수를 사용하여 azure-identity
라이브러리를 통해 액세스 토큰을 가져옵니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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')
설정 파일의 서비스 커넥터 서비스에서 추가한 환경 변수에서 Azure MySQL 데이터베이스 정보를 가져옵니다. 이전 단계에서 얻은 accessToken
을 사용하여 데이터베이스에 액세스합니다.
# 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
}
}
종속성을 설치합니다.
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"
코드에서 azidentity
를 통해 액세스 토큰을 가져오고 해당 토큰으로 Azure MySQL에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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)
}
종속성 설치
npm install --save @azure/identity
npm install --save mysql2
@azure/identity
및 서비스 커넥터 서비스에서 추가한 환경 변수의 Azure MySQL 데이터베이스 정보를 사용하여 액세스 토큰을 가져옵니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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');
});
코드 샘플에 대한 자세한 내용은 관리 ID를 사용하여 비밀 없이 App Service에서 Azure 데이터베이스에 연결을 참조하세요.
연결 문자열
Warning
사용 가능한 가장 안전한 인증 흐름을 사용하는 것이 권장됩니다. 이 절차에서 설명된 인증 흐름은 다른 흐름에는 없는 위험을 전달하며, 애플리케이션에서 매우 높은 신뢰 수준을 요구합니다. 이 흐름은 관리 ID와 같은 보다 안전한 다른 흐름을 실행할 수 없는 경우에만 사용되어야 합니다.
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_CONNECTIONSTRING |
ADO.NET MySQL 연결 문자열 |
Server=<MySQL-DB-name>.mysql.database.azure.com;Database=<MySQL-DB-name>;Port=3306;User Id=<MySQL-DBusername>;Password=<MySQL-DB-password>;SSL Mode=Required |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_CONNECTIONSTRING |
JDBC MySQL 연결 문자열 |
jdbc:mysql://<MySQL-DB-name>.mysql.database.azure.com:3306/<MySQL-DB-name>?sslmode=required&user=<MySQL-DB-username>&password=<Uri.EscapeDataString(<MySQL-DB-password>) |
애플리케이션 속성 |
설명 |
예제 값 |
spring.datasource.url |
Spring Boot JDBC 데이터베이스 URL |
jdbc:mysql://<MySQL-DB-name>.mysql.database.azure.com:3306/<MySQL-DB-name>?sslmode=required |
spring.datasource.username |
데이터베이스 사용자 이름 |
<MySQL-DB-username> |
spring.datasource.password |
데이터베이스 암호 |
MySQL-DB-password |
springboot
클라이언트 유형 연결을 만들면 서비스 커넥터 서비스에서 자동으로 spring.datasource.url
, spring.datasource.username
, spring.datasource.password
속성을 추가합니다. 따라서 Spring Boot 애플리케이션은 빈을 자동으로 추가할 수 있습니다.
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_NAME |
데이터베이스 이름 |
MySQL-DB-name |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
데이터베이스 사용자 이름 |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_PASSWORD |
데이터베이스 암호 |
MySQL-DB-password |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_NAME |
데이터베이스 이름 |
MySQL-DB-name |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
데이터베이스 사용자 이름 |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_PASSWORD |
데이터베이스 암호 |
MySQL-DB-password |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_CONNECTIONSTRING |
Go-sql-driver 연결 문자열 |
<MySQL-DB-username>:<MySQL-DB-password>@tcp(<server-host>:<port>)/<MySQL-DB-name>?tls=true |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
데이터베이스 사용자 이름 |
MySQL-DB-username |
AZURE_MYSQL_PASSWORD |
데이터베이스 암호 |
MySQL-DB-password |
AZURE_MYSQL_DATABASE |
데이터베이스 이름 |
<database-name> |
AZURE_MYSQL_PORT |
포트 번호 |
3306 |
AZURE_MYSQL_SSL |
SSL 옵션 |
true |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_DBNAME |
데이터베이스 이름 |
<MySQL-DB-name> |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_PORT |
포트 번호 |
3306 |
AZURE_MYSQL_FLAG |
SSL 또는 기타 플래그 |
MySQL_CLIENT_SSL |
AZURE_MYSQL_USERNAME |
데이터베이스 사용자 이름 |
<MySQL-DB-username> |
AZURE_MYSQL_PASSWORD |
데이터베이스 암호 |
<MySQL-DB-password> |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_DATABASE |
데이터베이스 이름 |
<MySQL-DB-name> |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USERNAME |
데이터베이스 사용자 이름 |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_PASSWORD |
데이터베이스 암호 |
<MySQL-DB-password> |
AZURE_MYSQL_SSLMODE |
SSL 옵션 |
required |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USERNAME |
데이터베이스 사용자 이름 |
MySQL-DB-username |
AZURE_MYSQL_PASSWORD |
데이터베이스 암호 |
MySQL-DB-password |
AZURE_MYSQL_DATABASE |
데이터베이스 이름 |
<database-name> |
AZURE_MYSQL_PORT |
포트 번호 |
3306 |
AZURE_MYSQL_SSL |
SSL 옵션 |
true |
샘플 코드
아래 단계와 코드를 참조하여 연결 문자열로 Azure Database for MySQL에 연결합니다.
- 종속성을 설치합니다. 지침에 따라 connector/NET MySQL을 설치합니다.
- 코드의 서비스 커넥터 서비스에서 추가한 환경 변수에서 MySQL 연결 문자열을 가져옵니다.
다음 단계를 따라 SSL을 통해 MySQL 서버에 암호화된 연결을 설정합니다.
using System;
using System.Data;
using MySql.Data.MySqlClient;
string connectionString = Environment.GetEnvironmentVariable("AZURE_MYSQL_CONNECTIONSTRING");
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
}
- 종속성을 설치합니다. 지침에 따라 Connector/J를 설치합니다.
- 코드의 서비스 커넥터 서비스에서 추가한 환경 변수에서 MySQL 연결 문자열을 가져옵니다.
다음 단계를 따라 SSL을 통해 MySQL 서버에 암호화된 연결을 설정합니다.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
String connectionString = System.getenv("AZURE_MYSQL_CONNECTIONSTRING");
try (Connection connection = DriverManager.getConnection(connectionString)) {
System.out.println("Connection successful!");
} catch (SQLException e) {
e.printStackTrace();
}
- 종속성을 설치합니다.
pom.xml
파일에 다음 종속성을 추가합니다.
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.azure.spring</groupId>
<artifactId>spring-cloud-azure-dependencies</artifactId>
<version>5.20.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.azure.spring</groupId>
<artifactId>spring-cloud-azure-starter-jdbc-mysql</artifactId>
</dependency>
</dependencies>
</dependencyManagement>
- 일반 Spring App 애플리케이션을 설정합니다. 자세한 내용은 이 섹션을 참조하세요.
다음 단계를 따라 SSL을 통해 MySQL 서버에 암호화된 연결을 설정합니다.
- 종속성을 설치합니다. 지침에 따라 Connector/Python을 설치합니다.
- 코드의 서비스 커넥터 서비스에서 추가한 환경 변수에서 MySQL 연결 정보를 가져옵니다.
다음 단계를 따라 SSL을 통해 MySQL 서버에 암호화된 연결을 설정합니다.
import os
import mysql.connector
host = os.getenv('AZURE_MYSQL_HOST')
user = os.getenv('AZURE_MYSQL_USER')
password = os.getenv('AZURE_MYSQL_PASSWORD')
database = os.getenv('Azure_MYSQL_NAME')
cnx = mysql.connector.connect(user=user, password=password,
host=host,
database=database)
cnx.close()
- 종속성을 설치합니다.
pip install django
- 설정 파일의 서비스 커넥터 서비스에서 추가한 환경 변수에서 MySQL 데이터베이스 정보를 가져옵니다.
다음 단계를 따라 SSL을 통해 MySQL 서버에 암호화된 연결을 설정합니다.
# in your setting file, eg. settings.py
host = os.getenv('AZURE_MYSQL_HOST')
user = os.getenv('AZURE_MYSQL_USER')
password = os.getenv('AZURE_MYSQL_PASSWORD')
database = os.getenv('AZURE_MYSQL_NAME')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host
}
}
- 종속성을 설치합니다.
go get -u github.com/go-sql-driver/mysql
- 코드의 서비스 커넥터 서비스에서 추가한 환경 변수에서 MySQL 연결 문자열을 가져옵니다.
다음 단계를 따라 SSL을 통해 MySQL 서버에 암호화된 연결을 설정합니다.
import (
"database/sql"
"fmt"
"os"
_ "github.com/go-sql-driver/mysql"
)
connectionString := os.Getenv("AZURE_MYSQL_CONNECTIONSTRING")
db, err := sql.Open("mysql", connectionString)
- 종속성을 설치합니다.
npm install mysql2
- 코드의 서비스 커넥터 서비스에서 추가한 환경 변수에서 MySQL 연결 정보를 가져옵니다.
다음 단계를 따라 SSL을 통해 MySQL 서버에 암호화된 연결을 설정합니다.
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.');
});
- 종속성을 설치합니다. 가이드에 따라 MySQLi를 설치합니다.
- 코드의 서비스 커넥터 서비스에서 추가한 환경 변수에서 MySQL 연결 정보를 가져옵니다.
다음 단계를 따라 SSL을 통해 MySQL 서버에 암호화된 연결을 설정합니다.
<?php
$host = getenv('AZURE_MYSQL_HOST');
$username = getenv('AZURE_MYSQL_USER');
$password = getenv('AZURE_MYSQL_PASSWORD');
$database = getenv('Azure_MYSQL_DBNAME');
$port = int(getenv('AZURE_MYSQL_PORT'));
# $flag = getenv('AZURE_MYSQL_FLAG');
$conn = mysqli_init();
# mysqli_ssl_set($conn,NULL,NULL,NULL,NULL,NULL);
mysqli_real_connect($conn, $host, $username, $password, $database, $port, NULL);
if (mysqli_connect_errno($conn)) {
die('Failed to connect to MySQL: ' . mysqli_connect_error());
}
echo 'Connected successfully to MySQL database!';
mysqli_close($conn);
?>
- 종속성을 설치합니다.
gem install mysql2
- 코드의 서비스 커넥터 서비스에서 추가한 환경 변수에서 MySQL 연결 정보를 가져옵니다.
다음 단계를 따라 SSL을 통해 MySQL 서버에 암호화된 연결을 설정합니다.
require 'mysql2'
require 'dotenv/load'
client = Mysql2::Client.new(
host: ENV['AZURE_MYSQL_HOST'],
username: ENV['AZURE_MYSQL_USERNAME'],
password: ENV['AZURE_MYSQL_PASSWORD'],
database: ENV['AZURE_MYSQL_DATABASE'],
# sslca: ca_path
)
client.close
서비스 주체
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<client-ID> |
AZURE_MYSQL_CLIENTSECRET |
클라이언트 암호 |
<client-secret> |
AZURE_MYSQL_TENANTID |
테넌트 ID |
<tenant-ID> |
AZURE_MYSQL_CONNECTIONSTRING |
ADO.NET MySQL 연결 문자열 |
Server=<MySQL-DB-name>.mysql.database.azure.com;Database=<MySQL-DB-name>;Port=3306;User Id=<MySQL-DBusername>;SSL Mode=Required |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<client-ID> |
AZURE_MYSQL_CLIENTSECRET |
클라이언트 암호 |
<client-secret> |
AZURE_MYSQL_TENANTID |
테넌트 ID |
<tenant-ID> |
AZURE_MYSQL_CONNECTIONSTRING |
JDBC MySQL 연결 문자열 |
jdbc:mysql://<MySQL-DB-name>.mysql.database.azure.com:3306/<MySQL-DB-name>?sslmode=required&user=<MySQL-DB-username> |
애플리케이션 속성 |
설명 |
예제 값 |
spring.datasource.azure.passwordless-enabled |
암호 없는 인증 사용 |
true |
spring.cloud.azure.credential.client-id |
클라이언트 ID |
<client-ID> |
spring.cloud.azure.credential.client-secret |
클라이언트 암호 |
<client-secret> |
spring.cloud.azure.credential.tenant-id |
테넌트 ID |
<tenant-ID> |
spring.datasource.url |
데이터베이스 URL |
jdbc:mysql://<MySQL-DB-name>.mysql.database.azure.com:3306/<MySQL-DB-name>?sslmode=required |
spring.datasource.username |
데이터베이스 사용자 이름 |
username |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_NAME |
데이터베이스 이름 |
MySQL-DB-name |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
데이터베이스 사용자 이름 |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<client-ID> |
AZURE_MYSQL_CLIENTSECRET |
클라이언트 암호 |
<client-secret> |
AZURE_MYSQL_TENANTID |
테넌트 ID |
<tenant-ID> |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_NAME |
데이터베이스 이름 |
MySQL-DB-name |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
데이터베이스 사용자 이름 |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<client-ID> |
AZURE_MYSQL_CLIENTSECRET |
클라이언트 암호 |
<client-secret> |
AZURE_MYSQL_TENANTID |
테넌트 ID |
<tenant-ID> |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<client-ID> |
AZURE_MYSQL_CLIENTSECRET |
클라이언트 암호 |
<client-secret> |
AZURE_MYSQL_TENANTID |
테넌트 ID |
<tenant-ID> |
AZURE_MYSQL_CONNECTIONSTRING |
Go-sql-driver 연결 문자열 |
<MySQL-DB-username>@tcp(<server-host>:<port>)/<MySQL-DB-name>?tls=true |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USER |
데이터베이스 사용자 이름 |
MySQL-DB-username |
AZURE_MYSQL_DATABASE |
데이터베이스 이름 |
<database-name> |
AZURE_MYSQL_PORT |
포트 번호 |
3306 |
AZURE_MYSQL_SSL |
SSL 옵션 |
true |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<client-ID> |
AZURE_MYSQL_CLIENTSECRET |
클라이언트 암호 |
<client-secret> |
AZURE_MYSQL_TENANTID |
테넌트 ID |
<tenant-ID> |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_DBNAME |
데이터베이스 이름 |
<MySQL-DB-name> |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_PORT |
포트 번호 |
3306 |
AZURE_MYSQL_FLAG |
SSL 또는 기타 플래그 |
MySQL_CLIENT_SSL |
AZURE_MYSQL_USERNAME |
데이터베이스 사용자 이름 |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<client-ID> |
AZURE_MYSQL_CLIENTSECRET |
클라이언트 암호 |
<client-secret> |
AZURE_MYSQL_TENANTID |
테넌트 ID |
<tenant-ID> |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_DATABASE |
데이터베이스 이름 |
<MySQL-DB-name> |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USERNAME |
데이터베이스 사용자 이름 |
<MySQL-DB-username>@<MySQL-DB-name> |
AZURE_MYSQL_SSLMODE |
SSL 옵션 |
required |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<client-ID> |
AZURE_MYSQL_CLIENTSECRET |
클라이언트 암호 |
<client-secret> |
AZURE_MYSQL_TENANTID |
테넌트 ID |
<tenant-ID> |
기본 환경 변수 이름 |
설명 |
예제 값 |
AZURE_MYSQL_HOST |
데이터베이스 호스트 URL |
<MySQL-DB-name>.mysql.database.azure.com |
AZURE_MYSQL_USERNAME |
데이터베이스 사용자 이름 |
MySQL-DB-username |
AZURE_MYSQL_DATABASE |
데이터베이스 이름 |
<database-name> |
AZURE_MYSQL_PORT |
포트 번호 |
3306 |
AZURE_MYSQL_SSL |
SSL 옵션 |
true |
AZURE_MYSQL_CLIENTID |
클라이언트 ID |
<identity-client-ID> |
AZURE_MYSQL_CLIENTSECRET |
클라이언트 암호 |
<client-secret> |
AZURE_MYSQL_TENANTID |
테넌트 ID |
<tenant-ID> |
샘플 코드
아래 단계와 코드를 참조하여 서비스 주체로 Azure Database for MySQL에 연결합니다.
.NET의 경우 암호 없는 연결을 지원하는 플러그 인 또는 라이브러리가 없습니다.
Azure.Identity와 같은 클라이언트 라이브러리를 사용하여 관리 ID 또는 서비스 주체에 대한 액세스 토큰을 가져올 수 있습니다. 그런 다음 액세스 토큰을 암호로 사용하여 데이터베이스에 연결할 수 있습니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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
pom.xml 파일에서 다음 종속성을 추가합니다.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity-extensions</artifactId>
<version>1.2.0</version>
</dependency>
환경 변수에서 연결 문자열을 가져와서 플러그 인 이름을 추가하여 데이터베이스에 연결합니다.
String url = System.getenv("AZURE_MYSQL_CONNECTIONSTRING");
String pluginName = "com.azure.identity.extensions.jdbc.mysql.AzureMysqlAuthenticationPlugin";
Properties properties = new Properties();
properties.put("defaultAuthenticationPlugin", pluginName);
properties.put("authenticationPlugins", pluginName);
// Uncomment the following lines corresponding to the authentication type you want to use.
// for user-assigned managed identity
// String clientId = System.getenv('AZURE_MYSQL_CLIENTID')
// properties.put("azure.clientId", clientId);
// For service principal
// String tenantId = System.getenv('AZURE_MYSQL_TENANTID')
// String clientId = System.getenv('AZURE_MYSQL_CLIENTID')
// String clientSecret = System.getenv('AZURE_MYSQL_CLIENTSECRET')
// properties.put("azure.clientId", clientId);
// properties.put("azure.clientSecret", clientSecret);
// properties.put("azure.tenantId", tenantId);
Connection connection = DriverManager.getConnection(url, properties);
자세한 내용은 Azure Database for MySQL - 유연한 서버에서 Java 및 JDBC 사용을 참조하세요.
종속성 설치
pip install azure-identity
# install Connector/Python https://dev.mysql.com/doc/connector-python/en/connector-python-installation.html
pip install mysql-connector-python
azure-identity
라이브러리를 통해 액세스 토큰으로 인증하고 서비스 커넥터에서 추가한 환경 변수의 연결 정보를 가져옵니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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()
종속성을 설치합니다.
pip install azure-identity
서비스 커넥터에서 추가한 환경 변수를 사용하여 azure-identity
라이브러리를 통해 액세스 토큰을 가져옵니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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')
설정 파일의 서비스 커넥터 서비스에서 추가한 환경 변수에서 Azure MySQL 데이터베이스 정보를 가져옵니다. 이전 단계에서 얻은 accessToken
을 사용하여 데이터베이스에 액세스합니다.
# 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
}
}
종속성을 설치합니다.
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"
코드에서 azidentity
를 통해 액세스 토큰을 가져오고 해당 토큰으로 Azure MySQL에 연결합니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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)
}
종속성 설치
npm install --save @azure/identity
npm install --save mysql2
@azure/identity
및 서비스 커넥터 서비스에서 추가한 환경 변수의 Azure MySQL 데이터베이스 정보를 사용하여 액세스 토큰을 가져옵니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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');
});
코드 샘플에 대한 자세한 내용은 관리 ID를 사용하여 비밀 없이 App Service에서 Azure 데이터베이스에 연결을 참조하세요.
다음 단계
설명서에 따라 서비스 커넥터에 대해 자세히 알아보세요.