この記事では、Service Connector を使用してアプリを Azure Database for PostgreSQL に接続するために使用できる、サポートされている認証方法、クライアント、サンプル コードについて説明します。 この記事では、サービス接続の作成時に取得した既定の環境変数の名前、値、構成についても説明します。
サポートされているコンピューティング サービス
Service Connector を使用すると、次のコンピューティング サービスを Azure Database for PostgreSQL に接続できます。
- Azure App Service
- Azure コンテナー アプリ
- Azure Functions (アジュール ファンクションズ)
- Azure Kubernetes Service (AKS)
- Azure Spring アプリ
サポートされている認証の種類とクライアントの種類
次の表は、Service Connector を使用してコンピューティング サービスを Azure Database for PostgreSQL に接続するためにサポートされている認証方法とクライアントの組み合わせを示しています。 "はい" はその組み合わせがサポートされていることを示し、"いいえ" はサポートされていないことを示します。
クライアント タイプ |
システム割り当てマネージド ID |
ユーザー割り当てマネージド ID |
シークレット/接続文字列 |
サービス プリンシパル |
。網 |
はい |
はい |
はい |
はい |
Go (pg) |
はい |
はい |
はい |
はい |
Java (JDBC) |
はい |
はい |
はい |
はい |
Java - Spring Boot (JDBC) |
はい |
はい |
はい |
はい |
Node.js(PG) |
はい |
はい |
はい |
はい |
PHP (ネイティブ) |
はい |
はい |
はい |
はい |
Python (psycopg2) |
はい |
はい |
はい |
はい |
Python-Django |
はい |
はい |
はい |
はい |
Ruby (ruby-pg) |
はい |
はい |
はい |
はい |
なし |
はい |
はい |
はい |
はい |
注
システム割り当てマネージド ID、ユーザー割り当てマネージド ID、サービス プリンシパルのみが Azure CLI でサポートされています。
既定の環境変数名またはアプリケーション プロパティとサンプル コード
接続の認証の種類とクライアントの種類に応じて、次の表の接続の詳細とサンプル コードを参照します。 名前付け規則の詳細については、Service Connector の内部の記事を参照してください。
システム割り当てマネージド ID
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
.NET PostgreSQL 接続文字列 |
Server=<PostgreSQL-server-name>.postgres.database.azure.com;Database=<database-name>;Port=5432;Ssl Mode=Require;User Id=<username>; |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
JDBC PostgreSQL 接続文字列 |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require&user=<username> |
アプリケーションのプロパティ |
説明 |
例値 |
spring.datasource.azure.passwordless-enabled |
パスワードレス認証を有効にする |
true |
spring.datasource.url |
データベース URL |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require |
spring.datasource.username |
データベース ユーザー名 |
username |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
psycopg2 接続文字列 |
dbname=<database-name> host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 sslmode=require user=<username> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_NAME |
データベース名 |
<database-name> |
AZURE_POSTGRESQL_HOST |
データベース ホスト URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
データベース ユーザー名 |
<username> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Go PostgreSQL 接続文字列 |
host=<PostgreSQL-server-name>.postgres.database.azure.com dbname=<database-name> sslmode=require user=<username> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_HOST |
データベース ホスト URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
データベース ユーザー名 |
<username> |
AZURE_POSTGRESQL_DATABASE |
データベース名 |
<database-name> |
AZURE_POSTGRESQL_PORT |
ポート番号 |
5432 |
AZURE_POSTGRESQL_SSL |
SSL オプション |
true |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
PHP ネイティブ PostgreSQL 接続文字列 |
host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Ruby PostgreSQL 接続文字列 |
host=<your-postgres-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_HOST |
データベース ホスト URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USERNAME |
データベース ユーザー名 |
<username> |
AZURE_POSTGRESQL_DATABASE |
データベース名 |
<database-name> |
AZURE_POSTGRESQL_PORT |
ポート番号 |
5432 |
AZURE_POSTGRESQL_SSL |
SSL オプション |
true |
サンプル コード
システム割り当てマネージド ID を使用して Azure Database for PostgreSQL に接続するには、以下の手順とコードを参照してください。
.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 については、App Service と Container Apps が内部的にアクセスできる REST エンドポイントを提供しており、2 つの環境変数 IDENTITY_ENDPOINT
と IDENTITY_HEADER
を定義することで、マネージド ID のトークンを取得できます。 詳細については、「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 接続情報を取得します。 これらを組み合わせて接続を確立します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
App Service と 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
ユーザー割り当てマネージド ID
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
.NET PostgreSQL 接続文字列 |
Server=<PostgreSQL-server-name>.postgres.database.azure.com;Database=<database-name>;Port=5432;Ssl Mode=Require;User Id=<username>; |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
JDBC PostgreSQL 接続文字列 |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require&user=<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:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require |
spring.datasource.username |
データベース ユーザー名 |
username |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
psycopg2 接続文字列 |
dbname=<database-name> host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 sslmode=require user=<username> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_NAME |
データベース名 |
<database-name> |
AZURE_POSTGRESQL_HOST |
データベース ホスト URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
データベース ユーザー名 |
<username> |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<<identity-client-ID>> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Go PostgreSQL 接続文字列 |
host=<PostgreSQL-server-name>.postgres.database.azure.com dbname=<database-name> sslmode=require user=<username> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_HOST |
データベース ホスト URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
データベース ユーザー名 |
<username> |
AZURE_POSTGRESQL_DATABASE |
データベース名 |
<database-name> |
AZURE_POSTGRESQL_PORT |
ポート番号 |
5432 |
AZURE_POSTGRESQL_SSL |
SSL オプション |
true |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<identity-client-ID> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
PHP ネイティブ PostgreSQL 接続文字列 |
host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<identity-client-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Ruby PostgreSQL 接続文字列 |
host=<your-postgres-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_HOST |
データベース ホスト URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USERNAME |
データベース ユーザー名 |
<username> |
AZURE_POSTGRESQL_DATABASE |
データベース名 |
<database-name> |
AZURE_POSTGRESQL_PORT |
ポート番号 |
5432 |
AZURE_POSTGRESQL_SSL |
SSL オプション |
true |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<identity-client-ID> |
サンプル コード
ユーザー割り当てマネージド ID を使用して Azure Database for PostgreSQL に接続するには、以下の手順とコードを参照してください。
.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 については、App Service と Container Apps が内部的にアクセスできる REST エンドポイントを提供しており、2 つの環境変数 IDENTITY_ENDPOINT
と IDENTITY_HEADER
を定義することで、マネージド ID のトークンを取得できます。 詳細については、「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 接続情報を取得します。 これらを組み合わせて接続を確立します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
App Service と 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
接続文字列
警告
Microsoft では、使用可能な最も安全な認証フローを使用することをお勧めします。 この手順で説明されている認証フローでは、アプリケーションで非常に高い信頼度が要求されるため、他のフローには存在しないリスクが伴います。 このフローは、マネージド ID など、より安全なフローが実行可能ではない場合にのみ使用してください。
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
.NET PostgreSQL 接続文字列 |
Server=<PostgreSQL-server-name>.postgres.database.azure.com;Database=<database-name>;Port=5432;Ssl Mode=Require;User Id=<username>; |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
JDBC PostgreSQL 接続文字列 |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require&user=<username>&password=<password> |
アプリケーションのプロパティ |
説明 |
例値 |
spring.datasource.url |
データベース URL |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require |
spring.datasource.username |
データベース ユーザー名 |
<username> |
spring.datasource.password |
データベースのパスワード |
<password> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
psycopg2 接続文字列 |
dbname=<database-name> host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 sslmode=require user=<username> password=<password> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_NAME |
データベース名 |
<database-name> |
AZURE_POSTGRESQL_HOST |
データベース ホスト URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
データベース ユーザー名 |
<username> |
AZURE_POSTGRESQL_PASSWORD |
データベースのパスワード |
<database-password> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Go PostgreSQL 接続文字列 |
host=<PostgreSQL-server-name>.postgres.database.azure.com dbname=<database-name> sslmode=require user=<username> password=<password> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_HOST |
データベース ホスト URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
データベース ユーザー名 |
<username> |
AZURE_POSTGRESQL_PASSWORD |
データベースのパスワード |
<password> |
AZURE_POSTGRESQL_DATABASE |
データベース名 |
<database-name> |
AZURE_POSTGRESQL_PORT |
ポート番号 |
5432 |
AZURE_POSTGRESQL_SSL |
SSL オプション |
true |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
PHP ネイティブ PostgreSQL 接続文字列 |
host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> password=<password> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Ruby PostgreSQL 接続文字列 |
host=<your-postgres-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> password=<password> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_HOST |
データベース ホスト URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USERNAME |
データベース ユーザー名 |
<username> |
AZURE_POSTGRESQL_DATABASE |
データベース名 |
<database-name> |
AZURE_POSTGRESQL_PORT |
ポート番号 |
5432 |
AZURE_POSTGRESQL_SSL |
SSL オプション |
true |
AZURE_POSTGRESQL_PASSWORD |
データベースのパスワード |
<password> |
サンプル コード
接続文字列を使用して Azure Database for PostgreSQL に接続するには、以下の手順とコードを参照してください。
-
Npgsql ガイダンスに従って依存関係をインストールする
- コードでは、Service Connector によって追加された環境変数から PostgreSQL 接続文字列を取得します。
using System;
using Npgsql;
string connectionString = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CONNECTIONSTRING");
using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
{
connection.Open();
}
-
pgJDBC ガイダンスに従って依存関係をインストールします。
- コードでは、Service Connector によって追加された環境変数から PostgreSQL 接続文字列を取得します。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
String connectionString = System.getenv("AZURE_POSTGRESQL_CONNECTIONSTRING");
Connection connection = null;
try {
connection = DriverManager.getConnection(connectionString);
System.out.println("Connection successful!");
} catch (SQLException e){
System.out.println(e.getMessage());
}
-
pom.xml
ファイルに次の依存関係を追加することによって、Spring Cloud Azure Starter JDBC PostgreSQL モジュールをインストールします。 Spring Cloud Azure のバージョンについては、ここを参照してください。
<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-postgresql</artifactId>
</dependency>
</dependencies>
</dependencyManagement>
- Spring Boot アプリケーションを設定します。詳細については、この セクションを参照してください。
-
psycopg2 ガイダンスに従って依存関係をインストールします。
- コードでは、Service Connector によって追加された環境変数から PostgreSQL 接続情報を取得します。
import os
import psycopg2
connection_string = os.getenv('AZURE_POSTGRESQL_CONNECTIONSTRING')
connection = psycopg2.connect(connection_string)
print("Connection established")
connection.close()
-
Django ガイダンスと psycopg2 ガイダンスに従って依存関係をインストールします。
pip install django
pip install psycopg2
- 設定ファイルで、Service Connector によって追加された環境変数から PostgreSQL データベース情報を取得します。
# in your setting file, eg. settings.py
host = os.getenv('AZURE_POSTGRESQL_HOST')
user = os.getenv('AZURE_POSTGRESQL_USER')
password = os.getenv('AZURE_POSTGRESQL_PASSWORD')
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
- コードでは、Service Connector によって追加された環境変数から PostgreSQL 接続文字列を取得します。
import (
"database/sql"
"fmt"
"os"
_ "github.com/lib/pq"
)
connectionString := os.Getenv("AZURE_POSTGRESQL_CONNECTIONSTRING")
conn, err := sql.Open("postgres", connectionString)
if err != nil {
panic(err)
}
conn.Close()
- 依存関係をインストールします。
npm install pg dotenv
- コードでは、Service Connector によって追加された環境変数から PostgreSQL 接続情報を取得します。
import { Client } from 'pg';
(async () => {
const client = new Client({
host: process.env.AZURE_POSTGRESQL_HOST,
user: process.env.AZURE_POSTGRESQL_USER,
password: process.env.AZURE_POSTGRESQL_PASSWORD,
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();
})();
- コードでは、Service Connector によって追加された環境変数から PostgreSQL 接続情報を取得します。
<?php
$conn_string = getenv('AZURE_POSTGRESQL_CONNECTIONSTRING');
$dbconn = pg_connect($conn_string);
?>
- 依存関係をインストールします。
gem install pg
- コードでは、Service Connector によって追加された環境変数から PostgreSQL 接続情報を取得します。
require 'pg'
require 'dotenv/load'
begin
conn = PG::Connection.new(
connection_string: ENV['AZURE_POSTGRESQL_CONNECTIONSTRING'],
)
rescue PG::Error => e
puts e.message
ensure
connection.close if connection
end
サービス プリンシパル
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
クライアント シークレット |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
テナント ID |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
.NET PostgreSQL 接続文字列 |
Server=<PostgreSQL-server-name>.postgres.database.azure.com;Database=<database-name>;Port=5432;Ssl Mode=Require;User Id=<username>; |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
クライアント シークレット |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
テナント ID |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
JDBC PostgreSQL 接続文字列 |
jdbc:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require&user=<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:postgresql://<PostgreSQL-server-name>.postgres.database.azure.com:5432/<database-name>?sslmode=require |
spring.datasource.username |
データベース ユーザー名 |
username |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
クライアント シークレット |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
テナント ID |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
psycopg2 接続文字列 |
dbname=<database-name> host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 sslmode=require user=<username> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_NAME |
データベース名 |
<database-name> |
AZURE_POSTGRESQL_HOST |
データベース ホスト URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
データベース ユーザー名 |
<username> |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
クライアント シークレット |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
テナント ID |
<tenant-ID> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
クライアント シークレット |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
テナント ID |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Go PostgreSQL 接続文字列 |
host=<PostgreSQL-server-name>.postgres.database.azure.com dbname=<database-name> sslmode=require user=<username> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_HOST |
データベース ホスト URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USER |
データベース ユーザー名 |
<username> |
AZURE_POSTGRESQL_DATABASE |
データベース名 |
<database-name> |
AZURE_POSTGRESQL_PORT |
ポート番号 |
5432 |
AZURE_POSTGRESQL_SSL |
SSL オプション |
true |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
クライアント シークレット |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
テナント ID |
<tenant-ID> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
クライアント シークレット |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
テナント ID |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
PHP ネイティブ PostgreSQL 接続文字列 |
host=<PostgreSQL-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
クライアント シークレット |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
テナント ID |
<tenant-ID> |
AZURE_POSTGRESQL_CONNECTIONSTRING |
Ruby PostgreSQL 接続文字列 |
host=<your-postgres-server-name>.postgres.database.azure.com port=5432 dbname=<database-name> sslmode=require user=<username> |
既定の環境変数名 |
説明 |
例値 |
AZURE_POSTGRESQL_HOST |
データベース ホスト URL |
<PostgreSQL-server-name>.postgres.database.azure.com |
AZURE_POSTGRESQL_USERNAME |
データベース ユーザー名 |
<username> |
AZURE_POSTGRESQL_DATABASE |
データベース名 |
<database-name> |
AZURE_POSTGRESQL_PORT |
ポート番号 |
5432 |
AZURE_POSTGRESQL_SSL |
SSL オプション |
true |
AZURE_POSTGRESQL_CLIENTID |
クライアント ID |
<identity-client-ID> |
AZURE_POSTGRESQL_CLIENTSECRET |
クライアント シークレット |
<client-secret> |
AZURE_POSTGRESQL_TENANTID |
テナント ID |
<tenant-ID> |
サンプル コード
サービス プリンシパルを使用して Azure Database for PostgreSQL に接続するには、以下の手順とコードを参照してください。
.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 については、App Service と Container Apps が内部的にアクセスできる REST エンドポイントを提供しており、2 つの環境変数 IDENTITY_ENDPOINT
と IDENTITY_HEADER
を定義することで、マネージド ID のトークンを取得できます。 詳細については、「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 接続情報を取得します。 これらを組み合わせて接続を確立します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
App Service と 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
次のステップ
Service Connector の詳細については、以下のチュートリアルに従ってください。