Azure Key Vault Secrets Simplified for Go Projects

Category

Tips & Tricks

Published

January 5, 2023

Good secret management is critical to maintaining a high-security level for your application and organization. One of the best ways to keep up with good security best practices is to use a secret/key/certificate store, and in the context of Azure, Azure Key Vault fulfills this purpose.

In this article, I will walk you through secret management in Azure for projects written in Go and show you how to use my library azcfg for easier secret retrievals.

Retrieving the Secrets

A couple of Azure services support loading Key Vault secrets into environment variables through reference (this will map them up as "Application settings," which is just another word for environment variables). To take the security of the secrets one step further, an alternative is to retrieve them from your application at runtime. That way, they will only exist in the application's memory, not on the platform it's running on. When doing the latter, the application needs additional code to communicate with the Key Vault.  

The SDK for Azure Key Vault secrets for Go is easy to use and has good documentation, but it still requires quite a bit of code to make use of it within applications.  

After writing implementations for secret retrieval and setting for many projects, I thought there must be a better way. Thus, I wrote the library azcfg (GitHub) to handle all this boilerplate code with the added flexibility to handle any data structure as the target container for the secrets.

Create an Azure Key Vault

First, let us create an Azure Key Vault and assign permissions to the currently logged-in user.

The next step is creating a user-assigned identity or Service Principal and assigning permissions to read the vault's secrets.

Creating example secrets:

Sample application

Now, it's time to write a sample application to show how to use the azcfg library.  

Create the project:

Edit main.go:

Note that the tags on the structs match the names of the secrets in the Key Vault.  

The final step is to add the environment variables AZURE_KEYVAULT_NAME, containing the name of the Key Vault and AZURE_CLIENT_ID of the user's assigned identity. However, if using a system-assigned identity, you can skip the environment variable for client ID.

Wrap-up

And that's how to use the azcfg library for secret retrieval!  

For more information on the library’s use and authentication options, check out the documentation or go directly to the source code that can be found on GitHub.

Written by

Karl Wallenius