services | platforms | author |
---|---|---|
azure-resource-manager |
dotnet |
devigned |
This sample explains how to manage your resources and resource groups in Azure using the Azure .NET SDK.
On this page
-
If you don't have it, install the .NET Core SDK.
-
Clone the repository.
git clone https://github.com/Azure-Samples/resource-manager-dotnet-resources-and-groups.git
-
Install the dependencies.
dotnet restore
-
Create an Azure service principal either through Azure CLI, PowerShell or the portal.
-
Export these environment variables using your subscription id and the tenant id, client id and client secret from the service principle that you created.
export AZURE_TENANT_ID={your tenant id} export AZURE_CLIENT_ID={your client id} export AZURE_CLIENT_SECRET={your client secret} export AZURE_SUBSCRIPTION_ID={your subscription id}
-
Run the sample.
dotnet run
The sample walks you through several resource and resource group management operations. It starts by setting up a ResourceManagementClient object using your subscription and credentials.
// Build the service credentials and Azure Resource Manager clients
var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, secret);
var resourceClient = new ResourceManagementClient(serviceCreds);
resourceClient.SubscriptionId = subscriptionId;
List the resource groups in your subscription.
resourceClient.ResourceGroups.List();
var keyVaultParams = new GenericResource{
Location = westus,
Properties = new Dictionary<string, object>{
{"tenantId", tenantId},
{"sku", new Dictionary<string, object>{{"family", "A"}, {"name", "standard"}}},
{"accessPolicies", Array.Empty<string>()},
{"enabledForDeployment", true},
{"enabledForTemplateDeployment", true},
{"enabledForDiskEncryption", true}
}
};
var keyVault = resourceClient.Resources.CreateOrUpdate(
resourceGroupName,
"Microsoft.KeyVault",
"",
"vaults",
"azureSampleVault",
"2015-06-01",
keyVaultParams);
resourceClient.ResourceGroups.ListResources(resourceGroupName);
You can export the resource group as a template and then use that to deploy your resources to Azure.
var exportResult = resourceClient.ResourceGroups.ExportTemplate(
resourceGroupName,
new ExportTemplateRequest{
Resources = new List<string>{"*"}
});
resourceClient.ResourceGroups.Delete(resourceGroupName);