C#: How to Create, Update, Delete and Check (If Exists) an Azure Resource Group in .NET?


csharp C#: How to Create, Update, Delete and Check (If Exists) an Azure Resource Group in .NET? c # cloud Microsoft Azure

csharp

Microsoft Azure Cloud organizes resources by Subscription ID and Resource Groups. In this post, we will find out the methods to check if a given resource group exists, to add or create or update an azure resource group, and delete a resource group.

We can use a Bearer Token credential to authenticate, or we can use other Credentials, such as DefaultCredentials.

Here is a way to obtain the Authorization/Authentication Bearer Token in C# via a Service Principal (requires Client ID, Tenant and Password):

1
2
3
4
5
6
7
8
9
10
11
private static string GetBearerToken(string tenant, string clientId, string password)
{
    var cc = new ClientCredential(clientId, string);
    var context = new AuthenticationContext("https://login.windows.net/" + tenant);
    var token = context.AcquireTokenAsync("https://management.azure.com/", cc);
    if (token == null)
    {
        throw new InvalidOperationException("Failed to obtain the JWT Bearer Token");
    }
    return token.Result.AccessToken;
}
private static string GetBearerToken(string tenant, string clientId, string password)
{
    var cc = new ClientCredential(clientId, string);
    var context = new AuthenticationContext("https://login.windows.net/" + tenant);
    var token = context.AcquireTokenAsync("https://management.azure.com/", cc);
    if (token == null)
    {
        throw new InvalidOperationException("Failed to obtain the JWT Bearer Token");
    }
    return token.Result.AccessToken;
}

With a Valid Bearer (JWT) Token, we can use the ArmClient to apply operations (Add, Create, Update, Delete) to a Microsoft Azure Resource Group.

C# .NET Programmatically Add or Create + Update and Azure Resource Group

If the resource group exists, then it will be updated, otherwise, the resource group will be created.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/// <summary>
/// Create a Resource Group
/// </summary>
/// <param name="subscriptionId">subscriptionId</param>
/// <param name="resourceGroup">resourceGroup</param>
/// <param name="region">region string e.g. ukwest</param>
/// <param name="token">a bearer token</param>
/// <returns></returns>
public static async Task<ResourceGroupResource> CreateResourceGroup(string subscriptionId, string resourceGroup, string region, string token)
{
    // First, initialize the ArmClient and get the default subscription
    var armClient = new ArmClient(new BearerTokenCredential(token));
    // Now we get a ResourceGroup collection for that subscription
    SubscriptionResource subscription = await armClient.GetSubscriptions().GetAsync(subscriptionId);
    ResourceGroupCollection rgCollection = subscription.GetResourceGroups();
    ResourceGroupData rgData = new ResourceGroupData(new AzureLocation(region));
    return (await rgCollection.CreateOrUpdateAsync(WaitUntil.Completed, resourceGroup, rgData)).Value;
}
/// <summary>
/// Create a Resource Group
/// </summary>
/// <param name="subscriptionId">subscriptionId</param>
/// <param name="resourceGroup">resourceGroup</param>
/// <param name="region">region string e.g. ukwest</param>
/// <param name="token">a bearer token</param>
/// <returns></returns>
public static async Task<ResourceGroupResource> CreateResourceGroup(string subscriptionId, string resourceGroup, string region, string token)
{
    // First, initialize the ArmClient and get the default subscription
    var armClient = new ArmClient(new BearerTokenCredential(token));
    // Now we get a ResourceGroup collection for that subscription
    SubscriptionResource subscription = await armClient.GetSubscriptions().GetAsync(subscriptionId);
    ResourceGroupCollection rgCollection = subscription.GetResourceGroups();
    ResourceGroupData rgData = new ResourceGroupData(new AzureLocation(region));
    return (await rgCollection.CreateOrUpdateAsync(WaitUntil.Completed, resourceGroup, rgData)).Value;
}

C# .NET Programmatically Check if an Azure Resource Group Exists

1
2
3
4
5
6
7
8
9
10
11
12
13
/// <summary>
/// Check if an Resource Group Exists
/// </summary>
/// <param name="subscriptionId">subscription ID</param>
/// <param name="resourceGroup">Name of resourceGroup</param>
/// <param name="token">a bearer token</param>
/// <returns>true or false</returns>
public static async Task<bool> ResourceGroupExists(string subscriptionId, string resourceGroup, string token)
{
    var armClient = new ArmClient(new BearerTokenCredential(token));
    SubscriptionResource subscription = await armClient.GetSubscriptions().GetAsync(subscriptionId);
    return subscription.GetResourceGroups().Exists(resourceGroup).Value;
}
/// <summary>
/// Check if an Resource Group Exists
/// </summary>
/// <param name="subscriptionId">subscription ID</param>
/// <param name="resourceGroup">Name of resourceGroup</param>
/// <param name="token">a bearer token</param>
/// <returns>true or false</returns>
public static async Task<bool> ResourceGroupExists(string subscriptionId, string resourceGroup, string token)
{
    var armClient = new ArmClient(new BearerTokenCredential(token));
    SubscriptionResource subscription = await armClient.GetSubscriptions().GetAsync(subscriptionId);
    return subscription.GetResourceGroups().Exists(resourceGroup).Value;
}

C# .NET Programmatically Delete an Azure Resource Group

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/// <summary>
/// Delete a Resource Group
/// </summary>
/// <param name="subscriptionId">subscriptionId</param>
/// <param name="resourceGroupName">resourceGroupName</param>
/// <param name="token">a bearer token</param>
public static async Task DeleteResourceGroup(string subscriptionId, string resourceGroupName, string token)
{
    // First, initialize the ArmClient and get the default subscription
    var armClient = new ArmClient(new BearerTokenCredential(token));
    // Now we get a ResourceGroup collection for that subscription
    SubscriptionResource subscription = await armClient.GetSubscriptions().GetAsync(subscriptionId);
    ResourceGroupResource resourceGroup = await subscription.GetResourceGroups().GetAsync(resourceGroupName);
    await resourceGroup.DeleteAsync(WaitUntil.Completed);
}
/// <summary>
/// Delete a Resource Group
/// </summary>
/// <param name="subscriptionId">subscriptionId</param>
/// <param name="resourceGroupName">resourceGroupName</param>
/// <param name="token">a bearer token</param>
public static async Task DeleteResourceGroup(string subscriptionId, string resourceGroupName, string token)
{
    // First, initialize the ArmClient and get the default subscription
    var armClient = new ArmClient(new BearerTokenCredential(token));
    // Now we get a ResourceGroup collection for that subscription
    SubscriptionResource subscription = await armClient.GetSubscriptions().GetAsync(subscriptionId);
    ResourceGroupResource resourceGroup = await subscription.GetResourceGroups().GetAsync(resourceGroupName);
    await resourceGroup.DeleteAsync(WaitUntil.Completed);
}

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
632 words
Last Post: Teaching Kids Programming - Number of Common Factors (Brute Force Algorithm + Greatest Common Divisor)
Next Post: Teaching Kids Programming - Recursive Algorithm to Count and Say a Number String

The Permanent URL is: C#: How to Create, Update, Delete and Check (If Exists) an Azure Resource Group in .NET?

Leave a Reply