根据我的测试,如果你想在控制台应用中使用sdkMicrosoft.Azure.Management.Blueprint来管理Azure蓝图,请参考步骤
- 创建服务主体
az login
# it will create a service pricipal and assign a contributor rolen to the sp
az ad sp create-for-rbac -n "MyApp" --scope "/subscriptions/<subscription id>" --sdk-auth
- 代码
private static string tenantId = "<the tenantId you copy >";
private static string clientId = "<the clientId you copy>";
private static string clientSecret= "<the clientSecre you copy>";
private static string subscriptionId = "<the subscription id you copy>";
static async Task Main(string[] args){
/*
install sdk Microsoft.Azure.Management.Blueprint and Microsoft.Identity.Client
*/
//get token
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithAuthority(AzureCloudInstance.AzurePublic, tenantId)
.WithClientSecret(clientSecret)
.Build();
string[] scopes = { "https://management.azure.com/.default" };
var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
TokenCredentials tokenCredentials = new TokenCredentials(result.AccessToken, "Bearer");
BlueprintManagementClient client = new BlueprintManagementClient(tokenCredentials);
var blueprint = new BlueprintModel()
{
DisplayName = "Sample Blueprint from Unittest",
TargetScope = Constants.BlueprintTargetScopes.Subscription,
ResourceGroups = new OrdinalStringDictionary<ResourceGroupDefinition>
{
{ "vNicResourceGroup", new ResourceGroupDefinition{ DisplayName="virtual-network-rg", Description = "All virutal network should save under this resource group." } }
},
Parameters = new OrdinalStringDictionary<ParameterDefinition>
{
{ "vNetName", new ParameterDefinition { Type = Constants.ParameterDefinitionTypes.String, DisplayName="default vNet for this subscription.", Description = "default vNet created by this blueprint.", DefaultValue = "defaultPublicVNet" } },
{ "defaultLocation", new ParameterDefinition { Type = Constants.ParameterDefinitionTypes.String, DisplayName="default Location", Description = "default location of resource created by this blueprint.", DefaultValue = "East US" } },
{ "defaultCostCenter", new ParameterDefinition { Type = Constants.ParameterDefinitionTypes.String, DisplayName="default CostCenter", Description = "default CostCenter for this subscription.", DefaultValue = "Contoso/IT/PROD/123456" } }
}
};
// create
var blueprintName = "subBPfromDotnetSDK";
Console.WriteLine("create Blueprint");
await client.Blueprints.CreateOrUpdateInSubscriptionAsync(subscriptionId, blueprintName, blueprint);
//get
var blueprintGet = await client.Blueprints.GetInSubscriptionAsync(subscriptionId, blueprintName);
Console.WriteLine(blueprintGet.DisplayName);
}