Getting started Azure SDK for Go
This article walks you through the fundamentals of using Azure SDK for Go, with a focus on creating storage drivers for use on the command line (CLI). This is a component of a larger research project to develop a CLI for backing up PostgreSQL databases and sending them to an Azure storage account.
Get Started with the Azure SDK for Go
Azure SDK for Go provides a wide range of functions, including managing Azure resources and processing data from Azure storage services. It is intended to be user-friendly, efficient, and adaptable to future development requirements. To use Azure SDK for Go, you must first install it with the command go:
go get -u github.com/Azure/azure-sdk-for-go/...Once installed, you can import the necessary packages into your Go code and start interacting with Azure services.
Setting Environment Variables
Before you begin interacting with Azure services, you must configure the following environment variables:
export AZURE_CLIENT_ID="__CLIENT_ID__"export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"export AZURE_TENANT_ID="__TENANT_ID__"export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"These environment variables are used by the Azure SDK for Go to authenticate your application to Azure.
Authentificating with Azure
To run code on an Azure subscription, you must authenticate to Azure. The azidentity package provides several options for authenticating to Azure, including client/secret, certificate, and managed identity. Here’s how to create an azidentity object:
cred, err := azidentity.NewDefaultAzureCredential(nil)if err != nil { // handle the error}This code uses previously configured environment variables to authenticate to Azure.
Creating Azure Resources
To configure Azure resources, you must first decide which client to use. For example, if you want to create a group, you can use ResourceGroupsClient. Once the client is defined, you can use it to make API calls to create, update, read, or delete Azure resources. Most of these operations are CRUD (create/read/update/delete) operations.
Here is an example of a resource group creation:
ctx := context.Background()resourceGroupName := "testresourcegroup"location := "francecentral"
resourceGroupParameters := armresources.ResourceGroup{ Location: to.StringPtr(location),}
_, err = resourceGroupsClient.CreateOrUpdate(ctx, resourceGroupName, resourceGroupParameters, nil)if err != nil { // handle the error}In this example, we will first create a context, then specify the name and location of the resource group we want to create. Next, we create a ResourceGroup object with the specified location, and finally we call the CreateOrUpdate method of the resourceGroupsClient to create the resource group.
Long-Running operations
Some Azure projects can take a long time to complete. The Azure SDK for Go provides support for long-running operations (LROs) via asynchronous calls. This list of functions starts with Start' and returns a Poller’ object. The poller object is used to periodically poll the service until it completes. Here’s an example:
ctx := context.Background()poller, err := client.BeginCreate(ctx, "resource_identifier", "additional_parameter")if err != nil { // handle the error...}resp, err = poller.PollUntilDone(ctx, nil)if err != nil { // handle the error...}fmt.Printf("LRO terminé")In this example, we first call an asynchronous function to create a client, which returns a Poller object. We then call the PollUntilDone function on the Poller object, which blocks until the original asynchronous function has finished.
Using the Azure SDK for Go to develop storage drivers
One of the most common uses of the Azure SDK for Go is to interact with Azure Blob Storage. This is a scalable, secure, and cost-effective solution for storing large amounts of unstructured data. In our case, we want to use it to store PostgreSQL database backups.
To interact with Azure Blob Storage, you must create an instance of the BlobServiceClient type. This instance represents the Azure storage account and is used to perform operations on blobs within the account. Here’s how to create a BlobServiceClient:
accountName, accountKey := "<azure-account-name>", "<azure-account-key>"credential, _ := azblob.NewSharedKeyCredential(accountName, accountKey)client, _ := azblob.NewServiceClient(fmt.Sprintf("https://%s.blob.core.windows.net/", accountName), credential, nil)In the code above, we first create a shared key with the Azure account name and key. Next, we create a new service client using the shared key.
Integrating Storage Drivers into a CLI
We can create a Go function that interacts with Azure Blob storage. This function can be extended to the CLI to provide an easy way to manage resources such as PostgreSQL database backups.
pisq is a CLI that uses the Azure SDK to upload backups to an Azure storage account. The `upload’ functionality is a clear example of this integration:
package azure
import ( "context" "fmt" "net/url" "os"
"github.com/charmbracelet/log"
"github.com/Azure/azure-storage-blob-go/azblob" )
func Upload(azureContainerName string, backupPath, azureAccountName string, azureAccountKey string) { credential, err := azblob.NewSharedKeyCredential(azureAccountName, azureAccountKey) if err != nil { log.Fatalf("Wrong authentication credentials: %v", err) } pipeline := azblob.NewPipeline(credential, azblob.PipelineOptions{}) URL, _ := url.Parse( fmt.Sprintf("https://%s.blob.core.windows.net/%s", azureAccountName, azureContainerName))
containerURL := azblob.NewContainerURL(*URL, pipeline)
file, err := os.Open(backupPath) if err != nil { log.Fatalf("The file already exists: %v", err) } defer file.Close()
blockBlobURL := containerURL.NewBlockBlobURL(backupPath) _, err = azblob.UploadFileToBlockBlob(context.Background(), file, blockBlobURL, azblob.UploadToBlockBlobOptions{}) if err != nil { log.Error("Failed to upload file to Azure Storage Account container", err) } else { log.Info("The upload was successful!") } }This function takes the container name, the path to the backup file, the Azure account name, and the Azure account key as parameters. It first creates a shared credential using the Azure account name and key. It then creates a pipeline using these credentials. A URL is generated for the Azure Blob storage container and a new container URL is created with the pipeline. The function then opens the backup file and creates a new blob URL. Finally, it uploads the backup file to the blob.
Conclusion
The Azure SDK for Go provides a powerful and efficient way to interact with Azure services. With this SDK, you can manage and interact with Azure resources directly from your Go application. Whether you’re configuring environment changes and authentication in Azure, provisioning Azure resources, or hosting long-term workloads, the Azure for Go SDK gives you everything you need.
The integration of this SDK with the CLI shows that it is possible to build drivers, as shown in pisq. This integration allows easy management of resources such as PostgreSQL database backups directly from the CLI.
As Azure continues to improve and expand its capabilities, the Azure SDK for Go becomes a reliable tool for developers. It is designed to keep pace with the growth of Azure, giving developers the tools they need to build, manage, and optimize their applications on the Azure platform.