Securing API Keys with PowerShell Secrets Management in Azure Key Vault

In today's ever-evolving digital landscape, where data and applications are increasingly interconnected, safeguarding sensitive information such as API keys has never been more important. These keys grant access to valuable resources and services, making them targets for malicious actors if not adequately protected. Azure Key Vault offers a robust and secure solution for managing and storing API keys and other secrets. This article explores how you can leverage PowerShell Secrets Management with Azure Key Vault to ensure the security of your API keys.

Prerequisites

The following prerequisites are required to follow along in the examples shown in this article.

Optional: An Azure subscription is required to use Azure Key Vault. To eliminate this requirement, you can use a local vault stored on your computer with PowerShell Secrets Management instead of Azure Key Vault. An OpenAI API subscription is required to use OpenAI's API. Although this is the example API key used in this article, you can store any API key in Azure Key Vault, eliminating this requirement. Other options are, however, outside the scope of this article.

Install the following PowerShell modules from the PowerShell Gallery.

1Install-Module -Name Az.KeyVault, Az.Resources, Microsoft.PowerShell.SecretManagement, PowerShellAI

Tip: You don't have to install the entire Az PowerShell module. You can install only the modules you need, such as in this article, where you'll use the Az.KeyVault and Az.Resources modules from the Az PowerShell module. Installing any module from the Az PowerShell module automatically installs the Az.Accounts module.

Region and tags

Store the location for the Azure region and the tags you'll assign to your Azure resources in variables.

1$location = 'southcentralus'
2$tags = @{owner='mikefrobbins'; purpose='classified'; environment='prod'; status='active'}

Create a resource group

Create a new Azure resource group. A resource group in Azure is a container that holds related resources for an Azure solution that you want to manage as a group. You decide which resources belong in a resource group based on what makes the most sense for your organization.

The following example creates a new Azure Resource Group named Roswell in the Azure region stored in the $location variable and assigns specific tags provided in the $tags variable.

1New-AzResourceGroup -Name Roswell -Location $location -Tag $tags
 1ResourceGroupName : Roswell
 2Location          : southcentralus
 3ProvisioningState : Succeeded
 4Tags              :
 5                    Name         Value
 6                    ===========  ============
 7                    status       active
 8                    owner        mikefrobbins
 9                    purpose      classified
10                    environment  prod
11
12ResourceId        : /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/Roswell

Create a Key Vault

Create a new Key Vault in Azure. Azure Key Vault is a cloud service that provides a secure store for secrets. It typically stores keys, passwords, certificates, and other secrets.

The following example creates a new Key Vault named Hanger18 in the Azure region stored in the $location variable and assigns specific tags provided in the $tags variable.

1New-AzKeyVault -VaultName Hanger18 -ResourceGroupName Roswell -Location $location -Tag $tags
 1Vault Name                          : Hanger18
 2Resource Group Name                 : Roswell
 3Location                            : southcentralus
 4Resource ID                         : /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/Roswell/providers/
 5                                      Microsoft.KeyVault/vaults/Hanger18
 6Vault URI                           : https://hanger18.vault.azure.net/
 7Tenant ID                           : 00000000-0000-0000-0000-000000000000
 8SKU                                 : Standard
 9Enabled For Deployment?             : False
10Enabled For Template Deployment?    :
11Enabled For Disk Encryption?        :
12Enabled For RBAC Authorization?     :
13Soft Delete Enabled?                : True
14Soft Delete Retention Period (days) : 90
15Purge Protection Enabled?           :
16Public Network Access               : Enabled
17Access Policies                     :
18                                      Tenant ID                                  : 00000000-0000-0000-0000-000000000000
19                                      Object ID                                  : 00000000-0000-0000-0000-000000000000
20                                      Application ID                             :
21                                      Display Name                               : Mike Robbins
22                                      Permissions to Keys                        : all
23                                      Permissions to Secrets                     : all
24                                      Permissions to Certificates                : all
25                                      Permissions to (Key Vault Managed) Storage : all
26
27
28Network Rule Set                    :
29                                      Default Action                             : Allow
30                                      Bypass                                     : AzureServices
31                                      IP Rules                                   :
32                                      Virtual Network Rules                      :
33
34Tags                                :
35                                      Name         Value
36                                      ===========  ============
37                                      status       active
38                                      owner        mikefrobbins
39                                      purpose      classified
40                                      environment  prod

Register the vault in PowerShell

Register the previously created Azure Key Vault as a secret vault in PowerShell. A secret vault is a storage location for secrets.

The following example registers the Azure Key Vault named Hanger18 as a secret vault in PowerShell named Area51. Specifying the DefaultVault parameter makes it the default vault in PowerShell. The PassThru parameter makes the command return the same information as running Get-SecretVault afterward.

1Register-SecretVault -Name Area51 -ModuleName Az.KeyVault -VaultParameters @{
2  AZKVaultName = 'Hanger18'
3  SubscriptionId = (Get-AzContext).Subscription.Id
4} -DefaultVault -PassThru
1Name  ModuleName  IsDefaultVault
2----  ----------  --------------
3Area51 Az.KeyVault True

Working with secrets

Try to use OpenAI's API to answer a question. The Get-GPT4Completion cmdlet is a part of Doug Finke's PowerShellAI module. The following example generates an error because you need to configure the PowerShellAI module to use your OpenAI API key.

1Get-GPT4Completion -Content 'What is the significance of Hanger18 at Roswell?'
1Exception: /Users/mikefrobbins/.local/share/powershell/Modules/PowerShellAI/0.9.1/Public/Invoke-OpenAIAPI.ps1:43
2Line |
3  43 |              throw 'Please set your OpenAI API key using Set-OpenAIKey …
4     |              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5     | Please set your OpenAI API key using Set-OpenAIKey or by configuring the $env:OpenAIKey environment variable
6     | (https://platform.openai.com/account/api-keys)

Store your OpenAI API key in a variable. The Read-Host cmdlet prompts you for input. The AsSecureString parameter masks the input, preventing it from being logged in your history, and stores the input as a secure string. The following example prompts you for your OpenAI API key and stores it as a secure string in a variable named $secret.

1$secret = Read-Host -Prompt 'Enter API key' -AsSecureString
1Enter API key: ***************************************************

Add your API key to the vault. The following example adds the OpenAI API key stored in the $secret variable to the Area51 vault and names it OpenAIKey.

1Set-Secret -Name OpenAIKey -Vault Area51 -SecureStringSecret $secret

Retrieve the secret from the vault. The following example retrieves the secret named OpenAIKey from the Area51 vault. Although it includes the Vault parameter, it's optional since you previously set the Area51 vault as the default.

1Get-Secret -Name OpenAIKey -Vault Area51
1System.Security.SecureString

Set the OpenAI API key for the PowerShellAI module using the Set-OpenAIKey cmdlet. The Set-OpenAIKey cmdlet is a part of the PowerShellAI module. The following example configures the PowerShellAI module to use the API key named OpenAIKey. It uses Get-Secret in a subcommand, inside parentheses, to retrieve your API key from the vault. The subcommand executes first, providing its results as the value for the Key parameter.

1Set-OpenAIKey -Key (Get-Secret -Name OpenAIKey)

Try to use OpenAI's API again to answer the same question. You've set the API key, so the command returns the answer to the question.

1Get-GPT4Completion -Content 'What is the significance of Hanger18 at Roswell?'
1Hanger 18 is often associated with conspiracy theories about UFOs and extraterrestrial life. The
2significance of Hanger 18 at Roswell is tied to the infamous Roswell incident in 1947, where a UFO
3supposedly crashed. Conspiracy theories believe that the wreckage and alien bodies were transported
4to Hanger 18 at Wright-Patterson Air Force Base, not Roswell, for examination and storage. However,
5there is no concrete evidence to support these claims.

Caution: Your secrets are only as secure as the system you've stored them in. You must take steps to maximize the security of your vaults and the data stored in them. For information on how to secure Azure Key Vault, see Azure Key Vault security.

Summary

In this article, you've learned how to secure API keys using PowerShell Secrets Management in Azure Key Vault. This article also highlights the significance of safeguarding API keys and securing the vaults where they're stored.

References