最近有一個需求,我要透過程式去控制 Azure AppService 中的 Application Settings ,但是網路上找,幾乎都是使用 Azure CLI 下 PS 指令比較多,這時候我就想溫馨的微軟應該會有出 SDK 來可以讓工程師來做到一些自己的自動化設定。
1. 因為文獻很少,我盡量簡單化,第一步你要先拿到憑證檔案內容,首先 你登入你的 azure portal ,點選上面的 Cloud Shell ,之後就點選 powershell 然後 輸入下列指令
az ad sp create-for-rbac --sdk-auth
之後就會給你下面內容
{
"clientId": "b52dd125-9272-4b21-9862-0be667bdf6dc",
"clientSecret": "ebc6e170-72b2-4b6f-9de2-99410964d2d0",
"subscriptionId": "ffa52f27-be12-4cad-b1ea-c2c241b6cceb",
"tenantId": "72f988bf-86f1-41af-91ab-2d7cd011db47",
"activeDirectoryEndpointUrl": "https://login.microsoftonline.com",
"resourceManagerEndpointUrl": "https://management.azure.com/",
"activeDirectoryGraphResourceId": "https://graph.windows.net/",
"sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
"galleryEndpointUrl": "https://gallery.azure.com/",
"managementEndpointUrl": "https://management.core.windows.net/"
}
把這存下來之後會用到
2. 在來就是寫程式的部分,開一個專案 並且下載套件
https://www.nuget.org/packages/Microsoft.Azure.Management.Fluent/ ,
https://www.nuget.org/packages/Microsoft.Azure.Management.ResourceManager.Fluent/,之後就是 將第一步驟得到的內容
複製到專案下,這邊我存檔名稱叫做 setting1.json 。
3. 接下來就是程式碼的部分,這邊我就直接註解在 程式碼裡面。
using System;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
namespace TestControlAppServiceAppSetting
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//取得憑證資料
var credentials = SdkContext.AzureCredentialsFactory.FromFile(AppDomain.CurrentDomain.BaseDirectory + "setting1.json");
//建立實體,載入憑證
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
//這 AppService Id 是在 AppService 中的 Properties 下的 Resource ID
var webApp = azure.AppServices.WebApps.GetById("/subscriptions/xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/RESOURCE-GROUP-NAME/providers/Microsoft.Web/sites/appservicename");
Console.WriteLine("AppServicePlanId -");
Console.WriteLine(webApp.AppServicePlanId) ;
Console.WriteLine("\r\n-\r\n");
Console.WriteLine("Read Appication Settings -");
var applicationSettings = webApp.GetAppSettings();
foreach (var settings in applicationSettings) {
Console.WriteLine(settings.Key + " , " + settings.Value.Value);
}
Console.WriteLine("\r\n-\r\n");
webApp.Update().WithAppSetting("CS_HELLO", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Apply();
}
}
}
Result:
reference:
https://docs.microsoft.com/en-us/dotnet/azure/authentication
https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.management.appservice.fluent.iwebapp?view=azure-dotnet
特別感謝 Dino 哥,指引一條明路。