이 문서에서는 서비스 커넥터를 사용하여 Azure Database for PostgreSQL에 앱을 연결하는 데 사용할 수 있는 지원되는 인증 방법, 클라이언트 및 샘플 코드에 대해 설명합니다. 이 문서에서는 서비스 연결을 만들 때 얻은 기본 환경 변수 이름, 값 및 구성도 찾을 수 있습니다.
지원되는 컴퓨팅 서비스
Service Connector를 사용하여 다음 컴퓨팅 서비스를 Azure Database for PostgreSQL에 연결할 수 있습니다.
- Azure App Service
- Azure Container Apps (Azure 컨테이너 애플리케이션)
- Azure 기능
- AKS(Azure Kubernetes Service)
- Azure Spring 앱
지원되는 인증 유형 및 클라이언트 유형
아래 표에서는 서비스 커넥터를 사용하여 컴퓨팅 서비스를 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
라이브러리를 사용하여 액세스 토큰을 가져오고 토큰을 암호로 사용합니다. 서비스 커넥터가 추가한 환경 변수에서 연결 정보를 가져옵니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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
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')
설정 파일의 서비스 커넥터 서비스가 추가한 환경 변수에서 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
를 사용하여 액세스 토큰을 가져오고 이 액세스 토큰을 암호로 사용하여 서비스 커넥터가 제공하는 연결 정보로 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
및 서비스 커넥터 서비스가 추가한 환경 변수의 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는 IDENTITY_ENDPOINT
및 IDENTITY_HEADER
환경 변수를 정의하여 관리 ID에 대한 토큰을 검색할 수 있는, 내부적으로 액세스 가능한 REST 엔드포인트를 제공합니다. 자세한 내용은 REST 엔드포인트 참조에서 확인할 수 있습니다.
ID 엔드포인트에 대한 HTTP GET 요청을 만들어 액세스 토큰을 가져오고, 쿼리에서 https://ossrdbms-aad.database.windows.net
을 resource
로 사용합니다. 사용자가 할당한 ID의 경우 서비스 커넥터가 추가한 환경 변수의 클라이언트 ID도 쿼리에 포함시킵니다.
서비스 주체의 경우 Azure AD 서비스 간 액세스 토큰 요청을 참조하여 액세스 토큰을 가져오는 자세한 방법을 확인합니다. 서비스 커넥터가 추가한 환경 변수의 서비스 주체 테넌트 ID, 클라이언트 ID 및 클라이언트 암호를 사용하여 https://ossrdbms-aad.database.windows.net/.default
범위까지 POST 요청을 만듭니다.
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 및 서비스 커넥터 서비스가 추가한 환경 변수의 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 서비스 간 액세스 토큰 요청을 참조하세요.
다음으로, 서비스 커넥터를 사용하기 전에 PostgreSQL 유연한 서버에서 테이블 및 시퀀스를 만든 경우 소유자로 연결하고 서비스 커넥터에서 만든 <aad-username>
에 사용 권한을 부여해야 합니다. 서비스 커넥터에 설정한 연결 문자열 또는 구성의 사용자 이름은 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
라이브러리를 사용하여 액세스 토큰을 가져오고 토큰을 암호로 사용합니다. 서비스 커넥터가 추가한 환경 변수에서 연결 정보를 가져옵니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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
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')
설정 파일의 서비스 커넥터 서비스가 추가한 환경 변수에서 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
를 사용하여 액세스 토큰을 가져오고 이 액세스 토큰을 암호로 사용하여 서비스 커넥터가 제공하는 연결 정보로 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
및 서비스 커넥터 서비스가 추가한 환경 변수의 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는 IDENTITY_ENDPOINT
및 IDENTITY_HEADER
환경 변수를 정의하여 관리 ID에 대한 토큰을 검색할 수 있는, 내부적으로 액세스 가능한 REST 엔드포인트를 제공합니다. 자세한 내용은 REST 엔드포인트 참조에서 확인할 수 있습니다.
ID 엔드포인트에 대한 HTTP GET 요청을 만들어 액세스 토큰을 가져오고, 쿼리에서 https://ossrdbms-aad.database.windows.net
을 resource
로 사용합니다. 사용자가 할당한 ID의 경우 서비스 커넥터가 추가한 환경 변수의 클라이언트 ID도 쿼리에 포함시킵니다.
서비스 주체의 경우 Azure AD 서비스 간 액세스 토큰 요청을 참조하여 액세스 토큰을 가져오는 자세한 방법을 확인합니다. 서비스 커넥터가 추가한 환경 변수의 서비스 주체 테넌트 ID, 클라이언트 ID 및 클라이언트 암호를 사용하여 https://ossrdbms-aad.database.windows.net/.default
범위까지 POST 요청을 만듭니다.
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 및 서비스 커넥터 서비스가 추가한 환경 변수의 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 서비스 간 액세스 토큰 요청을 참조하세요.
다음으로, 서비스 커넥터를 사용하기 전에 PostgreSQL 유연한 서버에서 테이블 및 시퀀스를 만든 경우 소유자로 연결하고 서비스 커넥터에서 만든 <aad-username>
에 사용 권한을 부여해야 합니다. 서비스 커넥터에 설정한 연결 문자열 또는 구성의 사용자 이름은 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_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
라이브러리를 사용하여 액세스 토큰을 가져오고 토큰을 암호로 사용합니다. 서비스 커넥터가 추가한 환경 변수에서 연결 정보를 가져옵니다. 아래 코드를 사용하는 경우 사용하려는 인증 유형에 대한 코드 조각 부분의 주석 처리를 제거합니다.
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
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')
설정 파일의 서비스 커넥터 서비스가 추가한 환경 변수에서 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
를 사용하여 액세스 토큰을 가져오고 이 액세스 토큰을 암호로 사용하여 서비스 커넥터가 제공하는 연결 정보로 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
및 서비스 커넥터 서비스가 추가한 환경 변수의 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는 IDENTITY_ENDPOINT
및 IDENTITY_HEADER
환경 변수를 정의하여 관리 ID에 대한 토큰을 검색할 수 있는, 내부적으로 액세스 가능한 REST 엔드포인트를 제공합니다. 자세한 내용은 REST 엔드포인트 참조에서 확인할 수 있습니다.
ID 엔드포인트에 대한 HTTP GET 요청을 만들어 액세스 토큰을 가져오고, 쿼리에서 https://ossrdbms-aad.database.windows.net
을 resource
로 사용합니다. 사용자가 할당한 ID의 경우 서비스 커넥터가 추가한 환경 변수의 클라이언트 ID도 쿼리에 포함시킵니다.
서비스 주체의 경우 Azure AD 서비스 간 액세스 토큰 요청을 참조하여 액세스 토큰을 가져오는 자세한 방법을 확인합니다. 서비스 커넥터가 추가한 환경 변수의 서비스 주체 테넌트 ID, 클라이언트 ID 및 클라이언트 암호를 사용하여 https://ossrdbms-aad.database.windows.net/.default
범위까지 POST 요청을 만듭니다.
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 및 서비스 커넥터 서비스가 추가한 환경 변수의 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 서비스 간 액세스 토큰 요청을 참조하세요.
다음으로, 서비스 커넥터를 사용하기 전에 PostgreSQL 유연한 서버에서 테이블 및 시퀀스를 만든 경우 소유자로 연결하고 서비스 커넥터에서 만든 <aad-username>
에 사용 권한을 부여해야 합니다. 서비스 커넥터에 설정한 연결 문자열 또는 구성의 사용자 이름은 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
다음 단계
서비스 커넥터에 대해 자세히 알아보려면 아래 나열된 자습서를 따르세요.