パスワードレス接続では、マネージド ID を使用して Azure サービスにアクセスします。 この方法では、マネージド ID のシークレットを手動で追跡および管理する必要はありません。 これらのタスクは、Azure 内部で安全に処理されます。
Service Connector を使用すると、Azure Spring Apps、Azure App Service、Azure Container Apps などのアプリ ホスティング サービスでマネージド ID を使用できます。 Service Connector では、Azure Database for PostgreSQL、Azure Database for MySQL、Azure SQL Database、Microsoft Fabric の SQL データベースなどのデータベース サービスも、マネージド ID を受け入れるように構成します。
このチュートリアルでは、Azure CLI を使用して以下のタスクを実了します。
- Azure CLI を使用して初期環境を確認する。
- Service Connector を使用してパスワードレス接続を作成する。
- Service Connector によって生成された環境変数または構成を使用して、データベース サービスにアクセスする。
前提条件
Azure CLI の使用を開始するには:
Service Connector パスワードレス拡張機能をインストールする
最新の Azure CLI 用 Service Connector パスワードレス拡張機能をインストールします。
az extension add --name serviceconnector-passwordless --upgrade
注
az version を実行して、拡張機能 "serviceconnector-passwordless" バージョンが "2.0.2" 以降であることを確認してください。 拡張機能のバージョンをアップグレードするには、最初に Azure CLI のアップグレードが必要になる場合があります。
パスワードレス接続を作成する
次に、Azure App Service を例として使用し、マネージド ID を使用する接続を作成します。
以下を使用する場合:
次の Azure CLI コマンドは --client-type パラメーターを使用します。パラメーターには java、dotnet、python などを使用できます。az webapp connection create postgres-flexible -h を実行して、サポートされているクライアントの種類を取得し、アプリケーションに一致するものを選択します。
az webapp connection create postgres-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $POSTGRESQL_HOST \
--database $DATABASE_NAME \
--user-identity client-id=XX subs-id=XX \
--client-type $CLIENT_TYPE
az webapp connection create postgres-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $POSTGRESQL_HOST \
--database $DATABASE_NAME \
--system-identity \
--client-type $CLIENT_TYPE
az webapp connection create postgres-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $POSTGRESQL_HOST \
--database $DATABASE_NAME \
--service-principal client-id=XX secret=XX\
--client-type $CLIENT_TYPE
Azure Database for MySQL - フレキシブル サーバーでは、Microsoft Entra 認証を有効にするためにユーザー割り当てマネージド ID が必要です。 詳細については、「 Azure Database for MySQL - フレキシブル サーバーの Microsoft Entra 認証を設定する」を参照してください。 次のコマンドを使用して、ユーザー割り当てマネージド ID を作成できます。
USER_IDENTITY_NAME=<YOUR_USER_ASSIGNED_MANAGED_IDENTITY_NAME>
IDENTITY_RESOURCE_ID=$(az identity create \
--name $USER_IDENTITY_NAME \
--resource-group $RESOURCE_GROUP \
--query id \
--output tsv)
重要
ユーザー割り当てマネージド ID を作成したら、グローバル管理者または特権ロール管理者に、この ID に対して次のアクセス許可を付与するように依頼します。
User.Read.All
GroupMember.Read.All
Application.Read.All
詳細については、「Active Directory 認証のアクセス許可」セクションを参照してください。
次に、Service Connector を使用して、システム割り当てマネージド ID で MySQL データベースにアプリを接続します。
次の Azure CLI コマンドでは、--client-type パラメーターを使用します。
az webapp connection create mysql-flexible -h を実行してサポートされているクライアントの種類を取得し、アプリケーションに一致するものを選択します。
az webapp connection create mysql-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $MYSQL_HOST \
--database $DATABASE_NAME \
--user-identity client-id=XX subs-id=XX mysql-identity-id=$IDENTITY_RESOURCE_ID \
--client-type java
az webapp connection create mysql-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $MYSQL_HOST \
--database $DATABASE_NAME \
--system-identity mysql-identity-id=$IDENTITY_RESOURCE_ID \
--client-type java
az webapp connection create mysql-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $MYSQL_HOST \
--database $DATABASE_NAME \
--service-principal client-id=XX secret=XX mysql-identity-id=$IDENTITY_RESOURCE_ID \
--client-type java
次の Azure CLI コマンドでは、--client-type パラメーターを使用します。
az webapp connection create sql -h を実行してサポートされているクライアントの種類を取得し、アプリケーションに一致するものを選択します。
az webapp connection create sql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $SQL_HOST \
--database $DATABASE_NAME \
--user-identity client-id=XX subs-id=XX \
--client-type dotnet
az webapp connection create sql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $SQL_HOST \
--database $DATABASE_NAME \
--system-identity \
--client-type dotnet
az webapp connection create sql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $SQL_HOST \
--database $DATABASE_NAME \
--service-principal client-id=XX secret=XX \
--client-type dotnet
次の Azure CLI コマンドでは、--client-type パラメーターを使用します。
az webapp connection create fabricsql -h を実行してサポートされているクライアントの種類を取得し、アプリケーションに一致するものを選択します。
az webapp connection create fabricsql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--fabric-workspace-uuid $FABRIC_WORKSPACE_UUID \
--fabric-sql-db-uuid $FABRIC_SQL_DB_UUID \
--user-identity client-id=XX subs-id=XX \
--client-type dotnet
az webapp connection create fabricsql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--fabric-workspace-uuid $FABRIC_WORKSPACE_UUID \
--fabric-sql-db-uuid $FABRIC_SQL_DB_UUID \
--system-identity \
--client-type dotnet
注
Microsoft Fabric で SQL データベースをターゲットにしている場合、サービス プリンシパルを使用したサービス接続はサポートされません。
この Service Connector コマンドは、バックグラウンドで次のタスクを完了します。
- システム割り当てマネージド ID を有効にするか、Azure App Service/Azure Spring Apps/Azure Container Apps によってホストされるアプリ
$APPSERVICE_NAME のユーザー ID を割り当てます。
- データベース サーバーに対して Microsoft Entra 認証を有効にします (有効になっていない場合)。
- Microsoft Entra 管理者を現在サインインしているユーザーに設定します。
- システム割り当てマネージド ID、ユーザー割り当てマネージド ID、またはサービス プリンシパルのデータベース ユーザーを追加します。 データベース
$DATABASE_NAME のすべての特権をこのユーザーに付与します。 ユーザー名は、前のコマンド出力の接続文字列で確認できます。
-
AZURE_MYSQL_CONNECTIONSTRING、AZURE_POSTGRESQL_CONNECTIONSTRING、AZURE_SQL_CONNECTIONSTRING、またはFABRIC_SQL_CONNECTIONSTRINGという名前の構成を、データベースの種類に基づいて Azure リソースに設定します。
- App Service の場合、構成は [ アプリの設定] ブレードで設定されます。
- Spring Apps の場合、構成はアプリケーションの起動時に設定されます。
- Container Apps の場合、構成は環境変数に設定されます。 すべての構成とその値は、Azure portal の [Service Connector ] ブレードで取得できます。
Service Connector は次の権限をユーザーに割り当てます。これらの権限を取り消し、要件に基づいて権限を調整できます。
GRANT ALL PRIVILEGES ON DATABASE "$DATABASE_NAME" TO "username";
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "username";
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO "username";
GRANT ALL PRIVILEGES ON $DATABASE_NAME.* TO 'username'@'%';
GRANT CONTROL ON DATABASE::"$DATABASE_NAME" TO "username";
ALTER ROLE db_datareader ADD MEMBER "username"
ALTER ROLE db_datawriter ADD MEMBER "username"
ALTER ROLE db_ddladmin ADD MEMBER "username"
Microsoft Entra 認証を使用してデータベースに接続する
接続を作成した後、アプリケーションで接続文字列を使って、Microsoft Entra 認証でデータベースに接続できます。 たとえば、次のソリューションを使って、Microsoft Entra 認証でデータベースに接続できます。
.NET の場合、パスワードレス接続をサポートするためのプラグインやライブラリはありません。
Azure.Identity などのクライアント ライブラリを使用して、マネージド ID またはサービス プリンシパルのアクセス トークンを取得できます。 次に、アクセス トークンをパスワードとして使用してデータベースに接続できます。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
using Azure.Identity;
using Azure.Core;
using Npgsql;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential();
// For user-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
// }
// );
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTSECRET");
// var sqlServerTokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Acquire the access token.
AccessToken accessToken = await sqlServerTokenProvider.GetTokenAsync(
new TokenRequestContext(scopes: new string[]
{
"https://ossrdbms-aad.database.windows.net/.default"
}));
// Combine the token with the connection string from the environment variables provided by Service Connector.
string connectionString =
$"{Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CONNECTIONSTRING")};Password={accessToken.Token}";
// Establish the connection.
using (var connection = new NpgsqlConnection(connectionString))
{
Console.WriteLine("Opening connection using access token...");
connection.Open();
}
pom.xml ファイルに次の依存関係を追加します。
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.5</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity-extensions</artifactId>
<version>1.2.0</version>
</dependency>
環境変数から接続文字列を取得し、データベースに接続するためのプラグイン名を追加します。
import java.sql.*;
String url = System.getenv("AZURE_POSTGRESQL_CONNECTIONSTRING");
String pluginName = "com.azure.identity.extensions.jdbc.postgresql.AzurePostgresqlAuthenticationPlugin";
Connection connection = DriverManager.getConnection(url + "&authenticationPluginClassName=" + pluginName);
詳細については、次のリソースを参照してください。
依存関係をインストールします。
pip install azure-identity
pip install psycopg2-binary
pip freeze > requirements.txt # Save the dependencies to a file
azure-identity ライブラリを使用してアクセス トークンを取得し、トークンをパスワードとして使用します。 Service Connector によって追加された環境変数から接続情報を取得します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# cred = DefaultAzureCredential()
# For user-assigned identity.
# managed_identity_client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal.
# tenant_id = os.getenv('AZURE_POSTGRESQL_TENANTID')
# client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# client_secret = os.getenv('AZURE_POSTGRESQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Acquire the access token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
# Combine the token with the connection string from the environment variables added by Service Connector to establish the connection.
conn_string = os.getenv('AZURE_POSTGRESQL_CONNECTIONSTRING')
conn = psycopg2.connect(conn_string + ' password=' + accessToken.token)
依存関係をインストールします。
pip install azure-identity
Service Connector によって追加された環境変数を使用することで、azure-identity ライブラリを使用してアクセス トークンを取得します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# credential = DefaultAzureCredential()
# For user-assigned identity.
# managed_identity_client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal.
# tenant_id = os.getenv('AZURE_POSTGRESQL_TENANTID')
# client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# client_secret = os.getenv('AZURE_POSTGRESQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Acquire the access token.
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
ファイルの設定で、Service Connector サービスによって追加された環境変数から Azure PostgreSQL データベース情報を取得します。 前の手順で取得した accessToken を使用し、データベースにアクセスします。
# In your setting file, eg. settings.py
host = os.getenv('AZURE_POSTGRESQL_HOST')
user = os.getenv('AZURE_POSTGRESQL_USER')
password = accessToken.token # this is accessToken acquired from above step.
database = os.getenv('AZURE_POSTGRESQL_NAME')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host,
'PORT': '5432', # Port is 5432 by default
'OPTIONS': {'sslmode': 'require'},
}
}
依存関係をインストールします。
go get github.com/lib/pq
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
コードで、azidentity を使用してアクセス トークンを取得してから、それを Service Connector によって提供された接続情報と共に、Azure PostgreSQL に接続するためのパスワードとして使用します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
import (
"database/sql"
"fmt"
"os"
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
_ "github.com/lib/pq"
)
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_POSTGRESQL_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_POSTGRESQL_CLIENTID")
// tenantid := os.Getenv("AZURE_POSTGRESQL_TENANTID")
// clientsecret := os.Getenv("AZURE_POSTGRESQL_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
if err != nil {
// error handling
}
// Acquire the access token
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"),
})
// Combine the token with the connection string from the environment variables added by Service Connector to establish the connection.
connectionString := os.Getenv("AZURE_POSTGRESQL_CONNECTIONSTRING") + " password=" + token.Token
conn, err := sql.Open("postgres", connectionString)
if err != nil {
panic(err)
}
conn.Close()
依存関係をインストールします。
npm install --save @azure/identity
npm install --save pg
コードで、@azure/identity を使用してアクセス トークンを取得し、Service Connector サービスによって追加された環境変数から PostgreSQL 接続情報を取得します。 これらを組み合わせて接続を確立します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity";
import { Client } from 'pg';
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_POSTGRESQL_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_POSTGRESQL_TENANTID;
// const clientId = process.env.AZURE_POSTGRESQL_CLIENTID;
// const clientSecret = process.env.AZURE_POSTGRESQL_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Acquire the access token.
var accessToken = await credential.getToken('https://ossrdbms-aad.database.windows.net/.default');
// Use the token and the connection information from the environment variables added by Service Connector to establish the connection.
(async () => {
const client = new Client({
host: process.env.AZURE_POSTGRESQL_HOST,
user: process.env.AZURE_POSTGRESQL_USER,
password: accesstoken.token,
database: process.env.AZURE_POSTGRESQL_DATABASE,
port: Number(process.env.AZURE_POSTGRESQL_PORT) ,
ssl: process.env.AZURE_POSTGRESQL_SSL
});
await client.connect();
await client.end();
})();
PHP の場合、パスワードレス接続用のプラグインやライブラリはありません。 マネージド ID またはサービス プリンシパルのアクセス トークンを取得し、データベースに接続するためのパスワードとして使用できます。 アクセス トークンは Azure REST API を使って取得できます。
コードで、お気に入りのライブラリを使用して REST API を使用してアクセス トークンを取得します。
ユーザー割り当て ID とシステム割り当て ID の場合、Azure App Service と Azure Container Apps は、 IDENTITY_ENDPOINT と IDENTITY_HEADERの 2 つの環境変数を定義することで、マネージド ID のトークンを取得するための内部アクセス可能な REST エンドポイントを提供します。 詳細については、 REST エンドポイント リファレンスを参照してください。
ID エンドポイントに対して HTTP GET 要求を行ってアクセス トークンを取得し、クエリの https://ossrdbms-aad.database.windows.net として resource を使います。 ユーザー割り当て ID の場合、Service Connector によって追加された環境変数のクライアント ID もクエリに含めてください。
サービス プリンシパルについては、 Azure AD のサービス間アクセス トークン要求を参照して、アクセス トークン を取得する方法の詳細を確認してください。 POST 要求を https://ossrdbms-aad.database.windows.net/.default のスコープにして、Service Connector によって追加された環境変数のサービス プリンシパルのテナント ID、クライアント ID、クライアント シークレットを指定します。
Service Connector サービスによって追加された環境変数のアクセス トークンと PostgreSQL 接続文字列を組み合わせて、接続を確立します。
<?php
$conn_string = sprintf("%s password=", getenv('AZURE_POSTGRESQL_CONNECTIONSTRING'), $access_token);
$dbconn = pg_connect($conn_string);
?>
Ruby の場合、パスワードレス接続用のプラグインやライブラリはありません。 マネージド ID またはサービス プリンシパルのアクセス トークンを取得し、データベースに接続するためのパスワードとして使用できます。 アクセス トークンは Azure REST API を使って取得できます。
依存関係をインストールします。
gem install pg
コードで、REST API を使用してアクセス トークンを取得し、Service Connector サービスによって追加された環境変数から PostgreSQL 接続情報を取得します。 これらを組み合わせて接続を確立します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
Azure App Service と Azure Container Apps には、マネージド ID のトークンを取得するための内部アクセス可能な REST エンドポイントが用意されています。 詳細については、 REST エンドポイント リファレンスを参照してください。
require 'pg'
require 'dotenv/load'
require 'net/http'
require 'json'
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# uri = URI(ENV['IDENTITY_ENDPOINT'] + '?resource=https://ossrdbms-aad.database.windows.net&api-version=2019-08-01')
# res = Net::HTTP.get_response(uri, {'X-IDENTITY-HEADER' => ENV['IDENTITY_HEADER'], 'Metadata' => 'true'})
# For user-assigned identity.
# uri = URI(ENV[IDENTITY_ENDPOINT] + '?resource=https://ossrdbms-aad.database.windows.net&api-version=2019-08-01&client_id=' + ENV['AZURE_POSTGRESQL_CLIENTID'])
# res = Net::HTTP.get_response(uri, {'X-IDENTITY-HEADER' => ENV['IDENTITY_HEADER'], 'Metadata' => 'true'})
# For service principal
# uri = URI('https://login.microsoftonline.com/' + ENV['AZURE_POSTGRESQL_TENANTID'] + '/oauth2/v2.0/token')
# params = {
# :grant_type => 'client_credentials',
# :client_id: => ENV['AZURE_POSTGRESQL_CLIENTID'],
# :client_secret => ENV['AZURE_POSTGRESQL_CLIENTSECRET'],
# :scope => 'https://ossrdbms-aad.database.windows.net/.default'
# }
# req = Net::HTTP::POST.new(uri)
# req.set_form_data(params)
# req['Content-Type'] = 'application/x-www-form-urlencoded'
# res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) do |http|
# http.request(req)
parsed = JSON.parse(res.body)
access_token = parsed["access_token"]
# Use the token and the connection string from the environment variables added by Service Connector to establish the connection.
conn = PG::Connection.new(
connection_string: ENV['AZURE_POSTGRESQL_CONNECTIONSTRING'] + " password=" + access_token,
)
サービス プリンシパル のアクセス トークンを取得する 方法の詳細については、Azure AD のサービス間アクセス トークン要求を参照してください。
次に、Service Connector を使用する前に PostgreSQL フレキシブル サーバーでテーブルとシーケンスを作成している場合、所有者として接続し、Service Connector によって作成された <aad-username> にアクセス許可を付与する必要があります。 Service Connector によって設定された接続文字列または構成からのユーザー名は aad_<connection name> のようになるはずです。 Azure portal を使用する場合、Service Type 列の横にある展開ボタンを選択し、値を取得します。 Azure CLI を使用する場合、CLI コマンドの出力の configurations をチェックします。
次に、クエリを実行してアクセス許可を付与します
az extension add --name rdbms-connect
az postgres flexible-server execute -n <postgres-name> -u <owner-username> -p "<owner-password>" -d <database-name> --querytext "GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO \"<aad-username>\";GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO \"<aad username>\";"
<owner-username> と <owner-password> は、他のユーザーにアクセス許可を付与できる既存のテーブルの所有者です。
<aad-username> は、サービス コネクタによって作成されたユーザーです。 これらを実際の値に置き換えます。
次のコマンドを使用して結果を検証します。
az postgres flexible-server execute -n <postgres-name> -u <owner-username> -p "<owner-password>" -d <database-name> --querytext "SELECT distinct(table_name) FROM information_schema.table_privileges WHERE grantee='<aad-username>' AND table_schema='public';" --output table
.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 ライブラリ経由で取得されるアクセス キーで認証し、Service Connector によって追加された環境変数から接続情報を取得します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
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
Service Connector によって追加された環境変数を使って、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')
ファイルの設定で、Service Connector サービスによって追加された環境変数から 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
Service Connector サービスによって追加された環境変数からの Azure MySQL データベース情報と @azure/identity を使用して、アクセス トークンを取得します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
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 データベースに接続する」を参照してください。
依存関係をインストールします。
dotnet add package Microsoft.Data.SqlClient
サービス コネクタによって追加された環境変数から Azure SQL Database 接続文字列を取得します。
using Microsoft.Data.SqlClient;
string connectionString =
Environment.GetEnvironmentVariable("AZURE_SQL_CONNECTIONSTRING")!;
using var connection = new SqlConnection(connectionString);
connection.Open();
詳細については、「 Active Directory マネージド ID 認証の使用」を参照してください。
pom.xml ファイルに次の依存関係を追加します。
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>10.2.0.jre11</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.7.0</version>
</dependency>
サービス コネクタによって追加された環境変数から Azure SQL Database 接続文字列を取得します。
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
public class Main {
public static void main(String[] args) {
// AZURE_SQL_CONNECTIONSTRING should be one of the following:
// For system-assigned managed identity: "jdbc:sqlserver://{SQLName}.database.windows.net:1433;databaseName={SQLDbName};authentication=ActiveDirectoryMSI;"
// For user-assigned managed identity: "jdbc:sqlserver://{SQLName}.database.windows.net:1433;databaseName={SQLDbName};msiClientId={UserAssignedMiClientId};authentication=ActiveDirectoryMSI;"
// For service principal: "jdbc:sqlserver://{SQLName}.database.windows.net:1433;databaseName={SQLDbName};user={ServicePrincipalClientId};password={spSecret};authentication=ActiveDirectoryServicePrincipal;"
String connectionString = System.getenv("AZURE_SQL_CONNECTIONSTRING");
SQLServerDataSource ds = new SQLServerDataSource();
ds.setURL(connectionString);
try (Connection connection = ds.getConnection()) {
System.out.println("Connected successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
詳細については、「 マネージド ID を使用してシークレットなしで App Service から Azure データベースに接続する」を参照してください。
Spring アプリケーションの場合、オプション --client-type springboot を使用して接続を作成すると、Service Connector によって、プロパティ spring.datasource.url が値形式 jdbc:sqlserver://<sql-server>.database.windows.net:1433;databaseName=<sql-db>;authentication=ActiveDirectoryMSI; を使用して Azure Spring Apps に設定されます。
チュートリアル「Azure SQL Database でパスワードレス接続を使用するように Java アプリケーションを移行する」に従って、アプリケーションを更新します。
spring.datasource.password 構成プロパティが以前に設定されている場合は必ず削除し、正しい依存関係を追加します。
依存関係をインストールします。
python -m pip install pyodbc
サービス コネクタによって追加された環境変数から Azure SQL Database 接続構成を取得します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。 コンピューティング サービスとして Azure Container Apps を使用している場合、またはコード スニペットの接続文字列が機能しない場合は、「 Python アプリケーションを移行して Azure SQL Database とのパスワードなしの接続を使用して アクセス トークンを使用して Azure SQL Database に接続する」を参照してください。
import os
import pyodbc
server = os.getenv('AZURE_SQL_SERVER')
port = os.getenv('AZURE_SQL_PORT')
database = os.getenv('AZURE_SQL_DATABASE')
authentication = os.getenv('AZURE_SQL_AUTHENTICATION')
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned managed identity.
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server=tcp:{server},{port};Database={database};Authentication={authentication};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30'
# For user-assigned managed identity.
# clientID = os.getenv('AZURE_SQL_USER')
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server=tcp:{server},{port};Database={database};UID={clientID};Authentication={authentication};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30'
# For service principal.
# user = os.getenv('AZURE_SQL_USER')
# password = os.getenv('AZURE_SQL_PASSWORD')
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server=tcp:{server},{port};Database={database};UID={user};PWD={password};Authentication={authentication};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30'
conn = pyodbc.connect(connString)
- 依存関係をインストールします。
npm install mssql
- サービス コネクタによって追加された環境変数から Azure SQL Database 接続構成を取得します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
import sql from 'mssql';
const server = process.env.AZURE_SQL_SERVER;
const database = process.env.AZURE_SQL_DATABASE;
const port = parseInt(process.env.AZURE_SQL_PORT);
const authenticationType = process.env.AZURE_SQL_AUTHENTICATIONTYPE;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned managed identity.
// const config = {
// server,
// port,
// database,
// authentication: {
// type: authenticationType
// },
// options: {
// encrypt: true
// }
// };
// For user-assigned managed identity.
// const clientId = process.env.AZURE_SQL_CLIENTID;
// const config = {
// server,
// port,
// database,
// authentication: {
// type: authenticationType
// },
// options: {
// encrypt: true,
// clientId: clientId
// }
// };
// For service principal.
// const clientId = process.env.AZURE_SQL_CLIENTID;
// const clientSecret = process.env.AZURE_SQL_CLIENTSECRET;
// const tenantId = process.env.AZURE_SQL_TENANTID;
// const config = {
// server,
// port,
// database,
// authentication: {
// type: authenticationType
// },
// options: {
// encrypt: true,
// clientId: clientId,
// clientSecret: clientSecret,
// tenantId: tenantId
// }
// };
this.poolconnection = await sql.connect(config);
詳細については、 Microsoft SQL Server へのクライアント プログラミングのホームページを参照してください。
依存関係をインストールします。
dotnet add package Microsoft.Data.SqlClient
Service Connector によって追加された環境変数から、Microsoft Fabric 接続文字列の SQL データベースを取得します。
using Microsoft.Data.SqlClient;
string connectionString =
Environment.GetEnvironmentVariable("FABRIC_SQL_CONNECTIONSTRING")!;
using var connection = new SqlConnection(connectionString);
connection.Open();
詳細については、「 Active Directory マネージド ID 認証の使用」を参照してください。
pom.xml ファイルに次の依存関係を追加します。
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>10.2.0.jre11</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.7.0</version>
</dependency>
Service Connector によって追加された環境変数から、Microsoft Fabric 接続文字列の SQL データベースを取得します。
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
public class Main {
public static void main(String[] args) {
// FABRIC_SQL_CONNECTIONSTRING should be one of the following:
// For system-assigned managed identity: "jdbc:sqlserver://<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;databaseName=<SQL-DB-name>-<Fabric-DB-Identifier>;authentication=ActiveDirectoryMSI;"
// For user-assigned managed identity: "jdbc:sqlserver://<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;databaseName=<SQL-DB-name>-<Fabric-DB-Identifier>;msiClientId=<msiClientId>;authentication=ActiveDirectoryMSI;"
String connectionString = System.getenv("FABRIC_SQL_CONNECTIONSTRING");
SQLServerDataSource ds = new SQLServerDataSource();
ds.setURL(connectionString);
try (Connection connection = ds.getConnection()) {
System.out.println("Connected successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
詳細については、「 マネージド ID を使用してシークレットなしで App Service から Azure データベースに接続する」を参照してください。
Spring アプリケーションの場合、オプション --client-type springbootを使用して接続を作成すると、Service Connector によって、値形式FABRIC_SQL_CONNECTIONSTRINGの環境変数jdbc:sqlserver://<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;databaseName=<SQL-DB-name>-<Fabric-DB-Identifier>;authentication=ActiveDirectoryMSI;が Azure Spring Apps に設定されます。
ユーザー割り当てマネージド ID の場合、 msiClientId=<msiClientId>; が追加されます。
チュートリアル「Azure SQL Database でパスワードレス接続を使用するように Java アプリケーションを移行する」に従って、アプリケーションを更新します。
spring.datasource.password構成プロパティが以前に設定されている場合は必ず削除し、正しい依存関係を追加してください。
spring:
datasource:
url: ${FABRIC_SQL_CONNECTIONSTRING}
依存関係をインストールします。
python -m pip install pyodbc
Service Connector によって追加された環境変数から、Microsoft Fabric 接続文字列の SQL データベースを取得します。 コンピューティング サービスとして Azure Container Apps を使用している場合、またはコード スニペット内の接続文字列が機能しない場合は、「パスワードなしの資格情報を使用して Microsoft Fabric の SQL データベースに接続するために、Azure SQL Database とのパスワードなしの接続を使用する Python アプリケーションを移行 する」を参照してください。
Authentication=ActiveDirectoryMSI; は、マネージド ID を使用して接続するときに接続文字列に必要です。
UID=<msiClientId> は、ユーザー割り当てマネージド ID を使用して接続するときにも接続文字列に必要です。
import os
import pyodbc, struct
from azure.identity import DefaultAzureCredential
connStr = os.getenv('FABRIC_SQL_CONNECTIONSTRING')
# System-assigned managed identity connection string format
# `Driver={ODBC Driver 17 for SQL Server};Server=tcp:<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;Database=<SQL-DB-name>-<Fabric-DB-Identifier>;Authentication=ActiveDirectoryMSI;`
# User-assigned managed identity connection string format
# `Driver={ODBC Driver 17 for SQL Server};Server=tcp:<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;Database=<SQL-DB-name>-<Fabric-DB-Identifier>;UID=<msiClientId>;Authentication=ActiveDirectoryMSI;`
conn = pyodbc.connect(connString)
- 依存関係をインストールします。
go mod init <YourProjectName>
go mod tidy
- Service Connector によって追加された環境変数から、Microsoft Fabric 接続文字列の SQL データベースを取得します。
package main
import (
"github.com/microsoft/go-mssqldb/azuread"
"database/sql"
"context"
"log"
"fmt"
"os"
)
var db *sql.DB
var connectionString = os.Getenv("FABRIC_SQL_CONNECTIONSTRING")
func main() {
var err error
// Create connection pool
db, err = sql.Open(azuread.DriverName, connectionString)
if err != nil {
log.Fatal("Error creating connection pool: ", err.Error())
}
ctx := context.Background()
err = db.PingContext(ctx)
if err != nil {
log.Fatal(err.Error())
}
fmt.Printf("Connected!\n")
}
詳細については、「 Golang を使用して Azure SQL Database のデータベースにクエリを実行する」を参照してください。
詳細については、「 Microsoft Fabric で SQL データベースに接続する」を参照してください。
Azure ホスティング サービスにアプリケーションをデプロイする
Azure ホスティング サービスにアプリケーションをデプロイします。 必要に応じて、これらのリソースのデプロイの詳細については、以下のガイドを参照してください。
ログを確認するか、アプリケーションを呼び出して、Azure データベースに正常に接続できるかどうかを確認します。
トラブルシューティング
権限
アクセス許可関連のエラーが発生した場合は、コマンド az account show を使用して Azure CLI サインイン済みユーザーを確認します。 必ず正しいアカウントを使用してサインインしてください。 次に、Service Connector とのパスワードレス接続を作成するために必要な可能性がある次のアクセス許可があることを確認します。
| 権限 |
操作 |
Microsoft.DBforPostgreSQL/flexibleServers/read |
データベース サーバーの情報を取得するために必要 |
Microsoft.DBforPostgreSQL/flexibleServers/write |
データベース サーバーに対して Microsoft Entra 認証を有効にするために必要 |
Microsoft.DBforPostgreSQL/flexibleServers/firewallRules/write |
ローカル IP アドレスがブロックされている場合にファイアウォール規則を作成するために必要 |
Microsoft.DBforPostgreSQL/flexibleServers/firewallRules/delete |
セキュリティの問題を回避するために、Service Connector によって作成されたファイアウォール規則を元に戻すために必要 |
Microsoft.DBforPostgreSQL/flexibleServers/administrators/read |
Azure CLI ログイン ユーザーがデータベース サーバーの Microsoft Entra 管理者であるかどうかを確認するために必要 |
Microsoft.DBforPostgreSQL/flexibleServers/administrators/write |
Azure CLI ログイン ユーザーをデータベース サーバーの Microsoft Entra 管理者として追加するために必要 |
| 権限 |
操作 |
Microsoft.DBforMySQL/flexibleServers/read |
データベース サーバーの情報を取得するために必要 |
Microsoft.DBforMySQL/flexibleServers/write |
指定されたユーザー割り当てマネージド ID をデータベース サーバーに追加するために必要 |
Microsoft.DBforMySQL/flexibleServers/firewallRules/write |
ローカル IP アドレスがブロックされている場合にファイアウォール規則を作成するために必要 |
Microsoft.DBforMySQL/flexibleServers/firewallRules/delete |
セキュリティの問題を回避するために、Service Connector によって作成されたファイアウォール規則を元に戻すために必要 |
Microsoft.DBforMySQL/flexibleServers/administrators/read |
Azure CLI ログイン ユーザーがデータベース サーバーの Microsoft Entra 管理者であるかどうかを確認するために必要 |
Microsoft.DBforMySQL/flexibleServers/administrators/write |
Azure CLI ログイン ユーザーをデータベース サーバーの Microsoft Entra 管理者として追加するために必要 |
| 権限 |
操作 |
Microsoft.Sql/servers/read |
データベース サーバーの情報を取得するために必要 |
Microsoft.Sql/servers/firewallRules/write |
ローカル IP アドレスがブロックされている場合にファイアウォール規則を作成するために必要 |
Microsoft.Sql/servers/firewallRules/delete |
セキュリティの問題を回避するために、Service Connector によって作成されたファイアウォール規則を元に戻すために必要 |
Microsoft.Sql/servers/administrators/read |
Azure CLI ログイン ユーザーがデータベース サーバーの Microsoft Entra 管理者であるかどうかを確認するために必要 |
Microsoft.Sql/servers/administrators/write |
Azure CLI ログイン ユーザーをデータベース サーバーの Microsoft Entra 管理者として追加するために必要 |
場合によっては、アクセス許可は必要ありません。 たとえば、Azure CLI で認証されたユーザーが既に SQL Server の Active Directory 管理者である場合、Microsoft.Sql/servers/administrators/write アクセス許可は必要ありません。
Microsoft Entra ID
エラー ERROR: AADSTS530003: Your device is required to be managed to access this resource. が発生した場合は、このデバイスを Microsoft Entra ID に参加させる方法について IT 部門に問い合わせてください。 詳細については、「 Microsoft Entra 参加済みデバイス」を参照してください。
Service Connector は、アカウントの情報とホスティング サービスのマネージド ID を取得するために、Microsoft Entra ID にアクセスする必要があります。 次のコマンドを使用して、デバイスが Microsoft Entra ID にアクセスできるかどうかを確認できます。
az ad signed-in-user show
対話形式でログインしない場合、エラーと Interactive authentication is needed が表示される場合もあります。 エラーを解決するには、az login コマンドを使用してログインします。
ネットワーク接続
データベース サーバーが Virtual Network 内にある場合は、Azure CLI コマンドを実行する環境が Virtual Network 内のサーバーにアクセスできることを確認します。
データベース サーバーが Virtual Network 内にある場合は、Azure CLI コマンドを実行する環境が Virtual Network 内のサーバーにアクセスできることを確認します。
データベース サーバーがパブリック アクセスを許可していない場合は、Azure CLI コマンドを実行する環境がプライベート エンドポイント経由でサーバーにアクセスできることを確認します。
次のステップ
Service Connector とパスワードレス接続の詳細については、次のリソースを参照してください。