Azure 앱 Configuration은 개발자가 애플리케이션 구성을 간단하고 안전하게 중앙 집중화하는 데 도움이 되는 관리형 서비스입니다. .NET 구성 공급자 라이브러리를 사용하면 관리되는 방식으로 Azure App Configuration 저장소에서 구성을 로드할 수 있습니다. 이 클라이언트 라이브러리는 .NET용 Azure SDK 위에 추가 기능을 추가합니다.
구성 로드
Azure App Configuration .NET 구성 공급자는 .NET 구성 시스템과 통합되므로 Azure App Configuration 저장소에서 구성 값을 쉽게 로드할 수 있습니다. 애플리케이션을 시작하는 동안 공급자를 추가하고 다른 구성 원본과 함께 사용할 수 있습니다.
.NET 구성 공급자를 사용하려면 패키지를 설치합니다.
dotnet add package Microsoft.Extensions.Configuration.AzureAppConfiguration
애플리케이션의 구성 공급자로 Azure App Configuration을 추가하기 위해 AddAzureAppConfiguration
에서 확장 메서드를 IConfigurationBuilder
호출합니다.
구성 공급자 라이브러리는 결합된 옵션 패턴 및 작성기 패턴을 구현하여 깔끔하고 선언적인 구성 방법을 AzureAppConfigurationOptions
제공합니다. 이 AddAzureAppConfiguration
메서드는 유창한 API를 통해 공급자를 구성할 수 있는 Action<AzureAppConfigurationOptions>
대리자 매개 변수를 허용합니다.
Azure App Configuration 저장소에 연결하려면 인스턴스에서 Connect
메서드를 AzureAppConfigurationOptions
호출합니다. 이 메서드는 메서드 체인을 사용하도록 설정하는 동일한 옵션 개체를 반환합니다.
DefaultAzureCredential
와 다른 토큰 자격 증명 구현을 사용하여 App Configuration 저장소에 인증할 수 있습니다.
지침에 따라 자격 증명에 App Configuration Data Reader 역할을 할당합니다.
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.AzureAppConfiguration;
using Azure.Identity;
var builder = new ConfigurationBuilder();
builder.AddAzureAppConfiguration(options =>
{
string endpoint = Environment.GetEnvironmentVariable("AppConfigurationEndpoint");
options.Connect(new Uri(endpoint), new DefaultAzureCredential());
});
var config = builder.Build();
Console.WriteLine(config["TestApp:Settings:Message"] ?? "Hello world!");
비고
ASP.NET Core 애플리케이션이나 백그라운드 서비스에서 AddAzureAppConfiguration
에서 builder.Configuration
을(를) 호출할 수 있습니다.
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddAzureAppConfiguration(options =>
{
string endpoint = Environment.GetEnvironmentVariable("Endpoint");
options.Connect(new Uri(endpoint), new DefaultAzureCredential());
});
구성 사용
Azure App Configuration 공급자를 추가한 후 다음과 같은 여러 가지 방법으로 구성 값에 액세스할 수 있습니다.
1. 직접 액세스
가장 간단한 방법은 인스턴스에서 직접 값을 검색하는 것입니다 IConfiguration
.
// Directly get the configuration
string message = configuration["TestApp:Settings:Message"];
IConfigurationSection settingsSection = configuration.GetSection("TestApp:Settings");
2. IConfiguration을 사용한 종속성 주입
서비스 또는 컨트롤러에서 IConfiguration
인터페이스를 직접 삽입하여 사용할 수 있습니다.
public class WeatherService
{
private readonly IConfiguration _configuration;
public WeatherService(IConfiguration configuration)
{
_configuration = configuration;
}
public Task<WeatherForecast> GetForecastAsync()
{
// Access configuration values directly from the injected instance
string apiEndpoint = _configuration["TestApp:Weather:ApiEndpoint"];
...
return Task.FromResult(new WeatherForecast());
}
}
3. 강력한 형식의 구성에 대한 옵션 패턴
// Define a strongly-typed settings class
public class Settings
{
public string BackgroundColor { get; set; }
public long FontSize { get; set; }
public string FontColor { get; set; }
public string Message { get; set; }
}
builder.Services.Configure<Settings>(builder.Configuration.GetSection("TestApp:Settings"));
.NET의 옵션 패턴에 대한 자세한 내용은 설명서를 참조하세요.
JSON 콘텐츠 형식 처리
App Configuration에서 JSON 키 값을 만들 수 있습니다. 콘텐츠 유형 "application/json"
이 포함된 키-값을 읽으면 구성 공급자는 이를 IConfiguration
내부의 개별 설정으로 변환합니다. 자세한 내용은 콘텐츠 형식을 사용하여 App Configuration에서 JSON 키 값을 저장하는 방법을 참조하세요.
선택기를 사용하여 특정 키 값 로드
기본적으로 구성 공급자는 App Configuration의 레이블 없이 모든 키-값을 로드합니다.
Select
에서 AzureAppConfigurationOptions
메서드를 호출하여 App Configuration 저장소에서 키-값을 선택적으로 로드할 수 있습니다.
builder.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(endpoint), new DefaultAzureCredential())
// Load configuration values with prefix "TestApp:" and no label
.Select("App:Settings:*")
// Load configuration values with prefix "TestApp:" and "Prod" label
.Select("App:Settings:*", "Prod")
// Load configuration values with prefix "TestApp:" and "Prod" label that have the tag "Group" with value "Contoso"
.Select("App:Settings:*", "Prod", new[] { "Group=Contoso" })
});
이 메서드는 Select
세 개의 매개 변수를 사용합니다. 첫 번째 매개 변수는 로드할 키를 지정하는 키 필터이고, 두 번째 매개 변수는 로드할 특정 레이블이 있는 키 값을 지정하는 레이블 필터이고, 세 번째 매개 변수는 로드할 키-값에 모두 있어야 하는 태그 필터 컬렉션을 지정합니다.
비고
여러 Select
호출에 겹치는 키가 포함된 경우 이후 호출이 이전 호출보다 우선합니다.
키 필터
키 필터 매개 변수는 포함할 구성 키를 결정합니다.
- 정확한 일치: 특정 문자열을 사용하면 필터와 정확히 일치하는 키만 일치합니다.
-
접두사 일치: 끝에 별표(
*
)를 추가하면 접두사 필터가 만들어집니다(예:App:Settings:*
"App:Settings:"로 시작하는 모든 키를 로드). -
여러 키 선택: 쉼표(
,
)를 사용하면 여러 명시적 키(예:Key1,Key2,Key3
)를 선택할 수 있습니다. -
예약 문자: 문자 별표(
*
), 쉼표(,
) 및 백슬래시(\
)는 예약되어 있으며 키 이름에 사용될 때 백슬래시로 이스케이프되어야 합니다(예: 키 필터a\\b\,\*c*
는 키가 .로a\b,*c
시작하는 모든 키 값을 반환함).
비고
와일드카드 접두사 일치를 동일한 Select
호출에서 쉼표로 구분된 필터와 결합할 수 없습니다. 예를 들어, abc*,def
는 지원되지 않지만, Select
와 abc*
를 사용하여 별도로 def
호출을 수행할 수 있습니다.
레이블 필터
레이블 필터 매개 변수는 특정 레이블이 있는 키 값을 선택합니다. 지정하지 않으면 기본 제공 LabelFilter.Null
이 사용됩니다.
비고
레이블 필터에는 문자 별표(*
) 및 쉼표(,
)가 지원되지 않습니다. 백슬래시(\
) 문자는 예약되어 있으며 다른 백슬래시(\
)를 사용하여 이스케이프해야 합니다.
태그 필터
태그 필터 매개 변수는 특정 태그가 있는 키-값을 선택합니다. 키-값은 필터에 지정된 모든 태그와 해당 값이 있는 경우에만 로드됩니다. 태그에 null 값을 지정하기 위해 기본 제공 TagValue.Null
을 사용할 수 있습니다.
비고
문자 별표(*
), 쉼표(,
), 및 백슬래시(\
)는 예약되어 있으며, 태그 필터에서 사용할 때 백슬래시로 이스케이프되어야 합니다.
키에서 접두사 자르기
특정 접두사를 사용하여 구성 값을 로드할 때 이 메서드를 사용하여 구성의 TrimKeyPrefix
키에서 이러한 접두사를 제거할 수 있습니다. 애플리케이션에 더 깔끔한 설정 키를 만들고, 동시에 App Configuration 저장소의 구성을 체계적으로 유지할 수 있습니다.
builder.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(endpoint), new DefaultAzureCredential())
// Load configuration values with prefix "TestApp:" and trim the prefix
.Select("TestApp:*")
.TrimKeyPrefix("TestApp:");
});
예를 들어, App Configuration 저장소에 TestApp:Settings:Message
라는 키가 포함되어 있으면, Settings:Message
접두사를 제거한 후 애플리케이션에서 TestApp:
로 액세스할 수 있습니다.
구성 설정 매핑
Azure App Configuration에서 키-값을 로드할 때, 공급자는 먼저 키-값을 ConfigurationSetting
개체로 가져온 후에 .NET 구성 시스템에 추가합니다.
Map
API를 사용하면 이 파이프라인 중에 이러한 설정을 변환하여 애플리케이션에 구성이 표시되는 방식을 제어할 수 있습니다.
이 Map
메서드는 ConfigurationSetting
개체를 받는 대리자 함수를 허용하며, 이를 수정할 수 있게 하고, ValueTask<ConfigurationSetting>
을 반환합니다. 이는 런타임 조건에 따라 키 이름 변환 또는 값 서식 지정에 특히 유용합니다.
다음 예제에서는 API를 사용하여 구성 키에서 Map
이중 밑줄(__
)을 콜론(:
)으로 바꾸는 방법을 보여 줍니다. 이 변환은 키가 App Configuration에서 대체 문자를 사용해야 하는 경우 .NET 구성에서 예상하는 계층 구조를 유지합니다.
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigEndpoint), new DefaultAzureCredential())
.Map((setting) =>
{
// Transform keys from format "App__Settings__Message" to "App:Settings:Message"
setting.Key = setting.Key.Replace("__", ":");
return new ValueTask<ConfigurationSetting>(setting);
});
});
팁 (조언)
작업은 Map
App Configuration에서 검색된 모든 구성 설정에 적용되므로 변환 논리가 가능한 모든 키 형식을 올바르게 처리해야 합니다.
구성 새로 고침
새로 고침을 구성하면 애플리케이션이 다시 시작하지 않고도 App Configuration 저장소에서 최신 값을 끌어올 수 있습니다. 메서드를 ConfigureRefresh
호출하여 키-값 새로 고침을 구성할 수 있습니다.
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigEndpoint), new DefaultAzureCredential())
// Load all keys that start with `TestApp:` and have no label
.Select(keyFilter: "TestApp:*", labelFilter: LabelFilter.Null)
.ConfigureRefresh(refreshOptions => {
// Trigger full configuration refresh when any selected key changes.
refreshOptions.RegisterAll()
// Check for changes no more often than every 60 seconds
.SetRefreshInterval(TimeSpan.FromSeconds(60));
});
});
ConfigureRefresh
메서드 내에서 선택한 키 값(TestApp으로 시작하고 레이블이 없는 키 값)의 변경 내용을 감지할 때마다 App Configuration 공급자에게 구성을 다시 로드하도록 지시하는 메서드를 호출 RegisterAll
합니다.
SetRefreshInterval
메서드 호출을 추가하여 구성 새로 고침 사이의 최소 시간을 지정할 수 있습니다. 설정하지 않으면 기본 새로 고침 간격은 30초입니다.
새로 고침 실행
새로 고침을 트리거하려면, TryRefreshAsync
의 IConfigurationRefresher
메서드를 호출해야 합니다. Azure App Configuration은 애플리케이션 아키텍처에 따라 구현을 위한 몇 가지 패턴을 제공합니다.
1. 종속성 주입
종속성 주입(ASP.NET Core 및 백그라운드 서비스 포함)을 사용하는 애플리케이션의 경우 새로 고침 서비스를 등록합니다.
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigEndpoint), new DefaultAzureCredential())
.ConfigureRefresh(refreshOptions =>
{
refreshOptions.RegisterAll()
.SetRefreshInterval(TimeSpan.FromSeconds(60));
})
});
// Register refresher service with the DI container
builder.Services.AddAzureAppConfiguration();
builder.Services.AddAzureAppConfiguration()
는 IConfigurationRefreshProvider
서비스를 DI 컨테이너에 추가하여 애플리케이션의 구성에 있는 모든 Azure App Configuration 원본의 새로 고침에 액세스할 수 있도록 합니다.
ASP.NET Core 애플리케이션
ASP.NET Core 애플리케이션의 Microsoft.Azure.AppConfiguration.AspNetCore
경우 패키지를 사용하여 기본 제공 미들웨어를 사용하여 요청 기반 구성 새로 고침 을 수행할 수 있습니다.
dotnet add package Microsoft.Azure.AppConfiguration.AspNetCore
서비스를 등록한 후, 들어오는 요청에 대해 구성을 자동으로 새로 고치기 위해 UseAzureAppConfiguration
을 애플리케이션 파이프라인에 추가하려면 AzureAppConfigurationRefreshMiddleware
을 호출하십시오.
...
// Call the AddAzureAppConfiguration to add refresher service to the DI container
builder.Services.AddAzureAppConfiguration();
var app = builder.Build();
// Call the app.UseAzureAppConfiguration() method as early as appropriate in your request pipeline so another middleware doesn't skip it
app.UseAzureAppConfiguration();
// Continue with other middleware registration
app.UseRouting();
...
AzureAppConfigurationRefreshMiddleware
구성된 새로 고침 간격에 따라 구성 변경 내용을 자동으로 확인합니다. 이 방법은 두 조건이 모두 충족될 때만 새로 고침되므로 효율적입니다. HTTP 요청이 수신되고 새로 고침 간격이 경과했습니다.
백그라운드 서비스
백그라운드 서비스의 경우, 서비스 IConfigurationRefresherProvider
를 주입하여 등록된 각 새로 고침기를 수동으로 새로 고칠 수 있습니다.
public class Worker : BackgroundService
{
private readonly IConfiguration _configuration;
private readonly IEnumerable<IConfigurationRefresher> _refreshers;
public Worker(IConfiguration configuration, IConfigurationRefresherProvider refresherProvider)
{
_configuration = configuration;
_refreshers = refresherProvider.Refreshers;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
foreach (IConfigurationRefresher refresher in _refreshers)
{
refresher.TryRefreshAsync();
}
...
}
}
2. 직접 액세스
종속성 주입을 사용하지 않는 애플리케이션의 경우 옵션에서 직접 새로 고침을 가져올 수 있습니다.
IConfigurationRefresher refresher = null;
var builder = new ConfigurationBuilder();
builder.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigEndpoint), new DefaultAzureCredential())
.ConfigureRefresh(refreshOptions =>
{
refreshOptions.RegisterAll();
});
// Store the refresher for later use
refresher = options.GetRefresher();
});
IConfiguration config = builder.Build();
// Later in your code, trigger refresh when needed
if (refresher != null)
{
await refresher.TryRefreshAsync()
}
Console.WriteLine(config["TestApp:Settings:Message"]);
비고
어떤 이유로든 새로 고침 호출이 실패하더라도 애플리케이션은 캐시된 구성을 계속 사용합니다. 애플리케이션 활동에 따라 짧은 기간 후에 또 다른 시도가 이루어집니다. 새로 고침은 구성된 새로 고침 간격이 경과하기 전에 no-op를 호출하기 때문에, 자주 호출되더라도 성능에 미치는 영향은 최소화됩니다.
sentinel 키에서 새로 고침
sentinel 키는 다른 모든 키의 변경을 완료한 후 업데이트하는 키입니다. 구성 공급자는 선택한 모든 키 값 대신 sentinel 키를 모니터링합니다. 변경이 감지되면 앱이 모든 구성 값을 새로 고칩니다.
이 방법은 여러 키-값을 업데이트할 때 유용합니다. 다른 모든 구성 변경이 완료된 후에만 sentinel 키를 업데이트하면 애플리케이션이 구성을 한 번만 다시 로드하고 일관성을 유지합니다.
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigEndpoint), new DefaultAzureCredential())
// Load all keys that start with `TestApp:` and have no label
.Select(keyFilter: "TestApp:*", labelFilter: LabelFilter.Null)
.ConfigureRefresh(refreshOptions => {
// Trigger full configuration refresh only if the `SentinelKey` changes.
refreshOptions.Register("SentinelKey", refreshAll: true);
});
});
중요합니다
키 값은 새로 고침 모니터링을 위해 자동으로 등록되지 않습니다.
ConfigureRefresh
를 명시적으로 호출한 다음 RegisterAll
메서드(로드된 모든 키를 모니터링)를 사용하거나 Register
메서드(개별 키를 모니터링)를 사용하여 키를 등록해야 합니다.
새로 고침 구성에 대한 자세한 내용은 자습서: ASP.NET Core 앱에서 동적 구성 사용으로 이동합니다.
기능 플래그
Azure App Configuration의 기능 플래그는 애플리케이션에서 기능 가용성을 제어하는 최신 방법을 제공합니다. 일반 구성 값과 달리 기능 플래그는 메서드를 사용하여 UseFeatureFlags
명시적으로 로드해야 합니다. 선택기를 사용하여 특정 기능 플래그를 로드하도록 구성 FeatureFlagOptions
하고 기능 플래그 새로 고침 간격을 설정할 수 있습니다.
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigEndpoint), new DefaultAzureCredential())
.UseFeatureFlags(featureFlagOptions => {
// Load feature flags with prefix "TestApp:" and "dev" label
featureFlagOptions.Select("TestApp:*", "dev")
// Check for changes no more often than every 60 seconds
.SetRefreshInterval(TimeSpan.FromSeconds(60));
});
});
메서드 내에서 UseFeatureFlags
메서드를 호출하여 Select
기능 플래그를 선택적으로 로드합니다.
키 필터, 레이블 필터 및 태그 필터를 사용하여 로드하려는 기능 플래그를 선택할 수 있습니다. 메서드가 호출되지 않으면 Select
UseFeatureFlags
기본적으로 레이블이 없는 모든 기능 플래그를 로드합니다.
키-값과 달리 기능 플래그는 명시적 ConfigureRefresh
호출 없이 새로 고침을 위해 자동으로 등록됩니다. 메서드를 통해 SetRefreshInterval
기능 플래그 새로 고침 사이의 최소 시간을 지정할 수 있습니다. 기본 새로 고침 간격은 30초입니다.
기능 관리
기능 관리 라이브러리는 기능 플래그를 기반으로 애플리케이션 기능을 개발하고 노출하는 방법을 제공합니다. 기능 관리 라이브러리는 구성 공급자 라이브러리와 함께 작동하도록 설계되었습니다.
Microsoft.FeatureManagement
패키지를 설치합니다.
dotnet add package Microsoft.FeatureManagement
AddFeatureManagement
을 호출하여 DI 컨테이너에 IVariantFeatureManager
및 관련 서비스를 등록할 수 있습니다. 이 등록을 통해 종속성 주입을 통해 애플리케이션 전체에서 기능 플래그 기능을 사용할 수 있습니다.
using Microsoft.FeatureManagement;
...
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigEndpoint), new DefaultAzureCredential());
// Use feature flags
options.UseFeatureFlags();
});
// Register feature management services
builder.Services.AddFeatureManagement();
다음 예제에서는 종속성 주입을 통해 기능 관리자 서비스를 사용하는 방법을 설명합니다.
public class WeatherForecastController : ControllerBase
{
private readonly IFeatureManager _featureManager;
public WeatherForecastController(IVariantFeatureManager featureManager)
{
_featureManager = featureManager;
}
[HttpGet]
public async Task<IActionResult> Get()
{
// Check if a feature flag is enabled
if (await _featureManager.IsEnabledAsync("WeatherForecast"))
{
var forecast = GenerateWeatherForecast();
return Ok(forecast);
}
return NotFound("Weather forecast feature is not available");
}
}
기능 관리 라이브러리를 사용하는 방법에 대한 자세한 내용은 기능 플래그 빠른 시작을 참조하세요.
Key Vault 참조
Azure 앱 Configuration은 Azure Key Vault에 저장된 비밀 참조를 지원합니다. App Configuration에서 Key Vault에 저장된 비밀에 매핑되는 키를 만들 수 있습니다. 비밀은 Key Vault에 안전하게 저장되지만 로드된 다른 구성처럼 액세스할 수 있습니다.
구성 공급자 라이브러리는 App Configuration에 저장된 다른 키와 마찬가지로 Key Vault 참조를 검색합니다. 클라이언트는 키를 Key Vault 참조로 인식하므로 고유한 콘텐츠 형식을 가지며 클라이언트는 Key Vault에 연결하여 애플리케이션에 대한 값을 검색합니다.
Key Vault에 연결
Key Vault에 ConfigureKeyVault
연결하는 방법을 구성하려면 메서드를 호출해야 합니다. Azure App Configuration 공급자는 Key Vault 비밀을 인증하고 액세스하는 여러 가지 방법을 제공합니다.
1. 인스턴스 등록 SecretClient
연결된 키 자격 증명 모음의 비밀에 대한 키 자격 증명 모음 참조를 확인하는 데 사용할 지정된 SecretClient
인스턴스를 등록할 수 있습니다.
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
...
var secretClient = new SecretClient(new Uri(vaultUri), new DefaultAzureCredential());
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigEndpoint), new DefaultAzureCredential())
.ConfigureKeyVault(kv =>
{
// Register a SecretClient instance
kv.Register(secretClient);
});
});
2. 자격 증명 사용
등록되지 않은 SecretClient
키 자격 모음에 인증하기 위해 사용할 수 있는 자격 증명을 설정할 수 있습니다.
using Azure.Identity;
...
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigEndpoint), new DefaultAzureCredential())
.ConfigureKeyVault(kv =>
{
// Use DefaultAzureCredential to access all Key Vaults
kv.SetCredential(new DefaultAzureCredential());
});
});
3. 사용자 지정 비밀 확인자 사용
등록된 SetSecretResolver
가 없거나 제공된 자격 증명이 Key Vault에 인증되지 않는 경우, 사용자 지정 비밀 확인자를 추가하기 위해 SecretClient
를 호출할 수도 있습니다. 이 메서드는 Key Vault URI를 비밀 값으로 확인하는 대리자 함수를 허용합니다. 다음 예제에서는 개발 중인 환경 변수에서 비밀을 검색하고 Key Vault에서 비밀을 가져오는 데 실패할 때 대체 값을 사용하는 비밀 확인자를 사용하는 방법을 보여 줍니다.
var secretClient = new SecretClient(new Uri(vaultUri), new DefaultAzureCredential());
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigEndpoint), new DefaultAzureCredential())
.ConfigureKeyVault(kv =>
{
// Add a custom secret resolver function
kv.SetSecretResolver(async (Uri secretUri) =>
{
if (builder.Environment.IsDevelopment())
{
return Environment.GetEnvironmentVariable("FALLBACK_SECRET_VALUE");
}
try
{
var secret = await secretClient.GetSecretAsync(secretName);
return secret.Value;
}
catch (Exception ex)
{
logger.LogWarning($"Failed to retrieve secret from {secretUri}: {ex.Message}");
return Environment.GetEnvironmentVariable("FALLBACK_SECRET_VALUE");
}
});
});
});
비고
Key Vault 참조를 확인할 때 공급자는 다음 순서를 따릅니다.
- 등록된
SecretClient
인스턴스 - 기본 자격 증명
- 사용자 지정 비밀 확인자
중요합니다
애플리케이션이 적절한 Key Vault 구성 없이 Key Vault 참조를 포함하는 키-값을 로드하는 경우 시작 시 예외 가 throw됩니다. Key Vault 액세스 또는 비밀 확인자를 올바르게 구성했는지 확인합니다.
팁 (조언)
사용자 지정 비밀 확인자를 사용하여 Key Vault 참조가 실수로 App Configuration 저장소에 추가되는 경우를 처리할 수 있습니다. 확인자는 Key Vault에 액세스할 때 적절한 자격 증명이 누락된 경우 예외를 발생시키는 대신, 대체 값을 제공하거나 경고를 기록하고 원활하게 문제를 처리할 수 있습니다.
Key Vault 비밀 새로 고침
Azure App Configuration을 사용하면 구성 새로 고침 주기와 독립적으로 비밀 새로 고침 간격을 구성할 수 있습니다. 이는 App Configuration의 Key Vault 참조 URI가 변경되지 않은 상태로 유지되지만 Key Vault의 기본 비밀이 보안 사례의 일부로 회전될 수 있기 때문에 보안에 매우 중요합니다.
애플리케이션에서 항상 가장 최신 비밀 값을 사용하도록 하려면 메서드를 구성합니다 SetSecretRefreshInterval
. 이렇게 하면 다음과 같은 경우 공급자가 Key Vault에서 새 비밀 값을 검색합니다.
- 귀하의 애플리케이션이
IConfigurationRefresher.TryRefreshAsync
를 호출합니다 - 비밀에 대해 구성된 새로 고침 간격이 경과했습니다.
이 메커니즘은 App Configuration 저장소에서 변경 내용이 감지되지 않은 경우에도 작동하여 애플리케이션이 갱신된 비밀과 동기화됩니다.
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigEndpoint), new DefaultAzureCredential())
.ConfigureKeyVault(kv =>
{
kv.SetCredential(new DefaultAzureCredential());
// Option 1: Set refresh interval for specific secrets
kv.SetSecretRefreshInterval("ApiKey", TimeSpan.FromHours(12));
// Option 2: Set a global refresh interval for all secrets with no refresh interval specified
kv.SetSecretRefreshInterval(TimeSpan.FromHours(24));
})
.ConfigureRefresh(refreshOptions => refreshOptions.RegisterAll());
});
Key Vault 참조를 사용하는 방법에 대한 자세한 내용은 자습서: ASP.NET Core 앱에서 Key Vault 참조 사용으로 이동합니다.
스냅샷
스냅샷 은 App Configuration 저장소의 키-값의 명명된 변경할 수 없는 하위 집합입니다. 스냅샷 구성하는 키-값은 키 및 레이블 필터를 사용하여 만드는 동안 선택됩니다. 스냅샷이 만들어지면 포함된 키-값은 변경되지 않은 상태로 유지됩니다.
스냅샷에서 키-값을 로드하도록 호출 SelectSnapshot
할 수 있습니다.
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigEndpoint), new DefaultAzureCredential());
// Select an existing snapshot by name. This adds all of the key-values and feature flags from the snapshot to this application's configuration.
options.SelectSnapshot("SnapshotName");
});
스냅샷 사용에 대한 자세한 내용은 스냅샷 만들기 및 사용으로 이동합니다.
시작 과정 다시 시도
구성 로드는 애플리케이션을 시작하는 동안 중요한 경로 작업입니다. 안정성을 보장하기 위해 Azure App Configuration 공급자는 초기 구성 로드 중에 강력한 재시도 메커니즘을 구현합니다. 이렇게 하면 성공적인 시작을 방해할 수 있는 일시적인 네트워크 문제로부터 애플리케이션을 보호할 수 있습니다.
메서드를 사용하여 이 동작을 사용자 지정할 수 있습니다.ConfigureStartupOptions
builder.Configuration.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(appConfigEndpoint), new DefaultAzureCredential())
.ConfigureStartupOptions(startupOptions =>
{
// Set the time-out for the initial configuration load
startupOptions.Timeout = TimeSpan.FromSeconds(60);
});
});
지리적 복제
지역에서 복제를 사용하는 방법에 대한 자세한 내용은 지역 복제 사용으로 이동하세요.
분산 추적
Azure App Configuration .NET 공급자에는 분산 추적에 대한 기본 제공 지원이 포함되어 있으므로 애플리케이션 전체에서 구성 작업을 모니터링하고 문제를 해결할 수 있습니다. 공급자는 구성 로드 및 구성 새로 고침 같은 주요 작업을 위해 ActivitySource
를 시작하는 "Microsoft.Extensions.Configuration.AzureAppConfiguration"
로 명명된 Activity
를 노출합니다.
다음 예제에서는 구성 공급자가 생성한 분산 추적을 캡처하고 모니터링하도록 OpenTelemetry를 구성하는 방법을 보여 줍니다.
List<Activity> exportedActivities = new();
builder.Services.AddOpenTelemetry()
.WithTracing(traceBuilder => {
traceBuilder.AddSource(["Microsoft.Extensions.Configuration.AzureAppConfiguration"]);
.AddInMemoryExporter(exportedActivities)
});
.NET의 OpenTelemetry에 대한 자세한 내용은 OpenTelemetry .NET 설명서를 참조하세요.
다음 단계
.NET 구성 공급자를 사용하는 방법을 알아보려면 다음 자습서를 계속 진행합니다.