Edit

Create an Azure Database for PostgreSQL flexible server by using the Azure SDK for .NET

In this quickstart, you learn how to use the Azure SDK libraries in .NET to create, update, and delete an Azure PostgreSQL flexible server. Azure Database for PostgreSQL is a managed service that you can use to run, manage, and scale highly available PostgreSQL databases in the cloud. By using the .NET SDK, you can provision an Azure Database for PostgreSQL flexible server, multiple servers, or multiple databases on a server.

Prerequisites

Azure.ResourceManager.PostgreSql library

The Azure.ResourceManager.PostgreSql library is part of the Azure SDK for .NET. It provides functionality for managing PostgreSQL flexible servers in Azure. By using this library, you can perform various operations related to PostgreSQL flexible servers, including but not limited to:

  • Create Azure PostgreSQL flexible servers:
    You can create new flexible servers with specified configurations such as location, SKU, storage, and version.

  • Update Azure PostgreSQL flexible servers:
    You can update existing PostgreSQL flexible servers, including changing configurations like administrator login, password, SKU, storage, and version.

  • Delete Azure PostgreSQL flexible servers:
    You can delete existing Azure PostgreSQL flexible servers.

  • Retrieve Azure PostgreSQL information:
    You can retrieve details about existing PostgreSQL flexible servers, including their configurations, status, and other metadata.

  • Manage databases:
    You can create, update, delete, and retrieve databases within the Azure PostgreSQL flexible server.

  • Manage firewall rules:
    You can create, update, delete, and retrieve firewall rules for an instance to control access.

  • Manage configuration settings:
    You can manage configuration settings for an Azure PostgreSQL flexible server, including retrieving and updating parameters.

Sign in to Azure

Before using the Azure SDK for .NET to create, update, or delete an Azure Database for PostgreSQL flexible server, log in to your Azure account by using the Azure CLI.

Run the authentication command

Authenticate to your account by using az CLI.

az login

Install required packages

Install the necessary packages by using the following commands:

dotnet add package Azure.Identity
dotnet add package Azure.ResourceManager
dotnet add package Azure.ResourceManager.PostgreSql

After installing these packages, ensure that each package is listed in the .csproj file before you execute the build and run commands.

To learn more about the .csproj file, see Web Deployment.

Note

If you have problems related to initial setup for .NET, see guide.

Create the project

Create a new .NET project by following the steps described in link.

Create the server

To create a PostgreSQL flexible server, create a file named CreateServer.cs with the following code.

using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.PostgreSql.FlexibleServers;
using Azure.ResourceManager.PostgreSql.FlexibleServers.Models;

namespace CreatePostgreSqlFlexibleServer
{
    class Program
 {
        static async Task Main(string[] args)
   {

            TokenCredential credential = new DefaultAzureCredential();
            ArmClient armClient = new ArmClient(credential);
            // Replace with your subscription ID
            string subscriptionId = "subscription-id";
            // Replace with your resource group name
            string resourceGroupName = "resource-group-name";
           // Replace with a unique server name
            string serverName = "server-name";
           // Replace with your desired region
            string location = "region-name";
          // Create the resource identifier for the resource group
            ResourceIdentifier resourceGroupId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
            ResourceGroupResource resourceGroup = await armClient.GetResourceGroupResource(resourceGroupId).GetAsync();
            // Prepare server data
            var serverData = new PostgreSqlFlexibleServerData(location)
            {
              AdministratorLogin = "admin-username",
              AdministratorLoginPassword = "<admin-password>",
              Version = "pgVersion",
              Storage = new PostgreSqlFlexibleServerStorage() { StorageSizeInGB = 128 },
              Sku = new PostgreSqlFlexibleServerSku("Standard_B1ms", PostgreSqlFlexibleServerSkuTier.Burstable),
           };
            try
            {
               ArmOperation<PostgreSqlFlexibleServerResource> operation = await resourceGroup.GetPostgreSqlFlexibleServers().CreateOrUpdateAsync(Azure.WaitUntil.Completed, serverName, serverData);
              PostgreSqlFlexibleServerResource serverResource = operation.Value;
              Console.WriteLine($"PostgreSQL flexible server '{serverResource.Data.Name}' created successfully.");
           }
            catch (Exception ex)
            {
               Console.WriteLine($"An error occurred: {ex.Message}");
            }
   }
  }
}

This example demonstrates creating a PostgreSQL flexible server using the Azure Resource Manager. PostgreSql library. You can similarly use other methods provided by the library to manage your PostgreSQL flexible servers and related resources.

Replace the following parameters in the code with your data:

  • subscription-id: Your Azure subscription ID.
  • resource-group-name: The name of your resource group.
  • server-name: A unique name for your PostgreSQL server.
  • location: The Azure region for your server.
  • admin-username: The administrator username.
  • admin-password: The administrator password.
  • pgVersion: The PostgreSQL version (for example, 11, 12, 13, 14, 15, or 16).

Authentication

The DefaultAzureCredential class tries to authenticate by using methods like environment variables, managed identities, or Azure CLI. Ensure you configure one of these methods.

Run the file

To run the file, build and execute the .cs file by using the .NET CLI. This process starts the creation, update, or deletion of the PostgreSQL instance according to the code.

Each time you change the .cs file, build and run the file.

Run the .cs file by using the following commands:

dotnet build
dotnet run

Note

Running this code starts the instance creation process, which might take a few minutes to complete.

Review deployed resources

To validate the deployment and review the deployed resources, use the Azure portal, Azure CLI, Azure PowerShell, and other tools.

Update server data

Create an UpdateServerData.cs file.

You can also update server data by using the Azure PostgreSQL .NET SDK.

For example, you can update the version, admin username, password, and other settings by using the CreateOrUpdateAsync method.

The CreateOrUpdateAsync method either creates a new instance if there's no instance with the same name or updates the existing instance with the new server data if it exists.

using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.PostgreSql.FlexibleServers;
using Azure.ResourceManager.PostgreSql.FlexibleServers.Models;

namespace UpdateServerData
{
    class Program
 {
        static async Task Main(string[] args)
   {

            TokenCredential credential = new DefaultAzureCredential();
            ArmClient armClient = new ArmClient(credential);
            // Replace with your subscription ID
            string subscriptionId = "subscription-id";
            // Replace with your resource group name
            string resourceGroupName = "resource-group-name";
            // Replace with a unique server name
            string serverName = "server-name";
            // Replace with your desired region
            string location = "region-name";
            ResourceIdentifier resourceGroupId = ResourceGroupResource.CreateResourceIdentifier(subscriptionId, resourceGroupName);
            ResourceGroupResource resourceGroup = await armClient.GetResourceGroupResource(resourceGroupId).GetAsync();
            // Prepare server data
            var serverData = new PostgreSqlFlexibleServerData(location)
           {
              // Updating version from a lower version to a higher version
              Version = "16",
           };
            try
             {
               ArmOperation<PostgreSqlFlexibleServerResource> operation = await resourceGroup.GetPostgreSqlFlexibleServers().CreateOrUpdateAsync(Azure.WaitUntil.Completed, serverName, serverData);
               PostgreSqlFlexibleServerResource serverResource = operation.Value;
               Console.WriteLine($"PostgreSQL flexible server '{serverResource.Data.Name}' updated successfully.");
            }
            catch (Exception ex)
            {
              Console.WriteLine($"An error occurred: {ex.Message}");
            }
   }
  }
}

Run the file and review the changes made in the resource by using the UpdateServerData.cs file.

Clean up resources

You can clean up the created flexible servers by deleting the flexible server with the Azure SDK for .NET.

Create a DeleteServer.cs file and add the following code.

using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.PostgreSql.FlexibleServers;
using Azure.ResourceManager.PostgreSql.FlexibleServers.Models;

namespace DeleteServer
{
    class Program
  {
        static async Task Main(string[] args)
   {

            // Replace with your subscription ID
            string subscriptionId = "subscription-id";
            // Replace with your resource group name
            string resourceGroupName = "resource-group-name";
            // Replace with a unique server name
            string serverName = "server-name";
            var credential = new DefaultAzureCredential();
            var armClient = new ArmClient(credential);
            try
            {
                // Get the PostgreSQL flexible server resource
                var postgresServerResourceId = PostgreSqlFlexibleServerResource.CreateResourceIdentifier(subscriptionId, resourceGroupName, serverName);
                var postgresServer = armClient.GetPostgreSqlFlexibleServerResource(postgresServerResourceId);
                // Delete the server
                await postgresServer.DeleteAsync(Azure.WaitUntil.Completed);
                Console.WriteLine($"PostgreSQL flexible server '{serverName}' deleted successfully.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
   }
  }
}

Replace the following parameters with your data:

  • subscription-id: Your own subscription ID.
  • resource-group-name: The name of the resource group you want to use. The script creates a new resource group if it doesn't exist.
  • server-name: The name of the Azure database flexible server that you created.

You can also delete the resource group created through the portal, CLI, or PowerShell. Follow the steps mentioned in the CLI and PowerShell section if you want to delete it by using CLI or PowerShell.

Replace placeholders with your details and run the file.

Alternatively, you can remove the resource group by using:

  • Azure CLI: az group delete --name <resource_group>
  • PowerShell: Remove-AzResourceGroup -Name <resource_group>
  • Azure portal: Navigate to the resource group and delete it.