Questions? Feedback? powered by Olark live chat software
Spring over navigation

Manage Azure resources and resource groups with .NET

Sidst opdateret: 27-10-2016
Bidragydere:
Rediger på GitHub

This sample explains how to manage your resources and resource groups in Azure using the Azure .NET SDK.

On this page

Run this sample

  1. If you don't have it, install the .NET Core SDK.

  2. Clone the repository.

    git clone https://github.com/Azure-Samples/resource-manager-dotnet-resources-and-groups.git
    
  3. Install the dependencies.

    dotnet restore
    
  4. Create an Azure service principal either through Azure CLI, PowerShell or the portal.

  5. Add these environment variables to your .env file 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}
    
  6. Run the sample.

    dotnet run
    

What is program.cs doing?

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 resource groups

List the resource groups in your subscription.

resourceClient.ResourceGroups.List();

Create a key vault in the resource group

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);

List resources within the group

resourceClient.ResourceGroups.ListResources(resourceGroupName);

Export the resource group template

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>{"*"}
    });

Delete a resource group

resourceClient.ResourceGroups.Delete(resourceGroupName);