miserable
miserable

Reputation: 727

Store key and secret in Azure key-vault

We want to store our AWS key and secret on azure key vault because our VM's are on the Azure cloud.

All we want is to keep the AWS secret and key in the Azure key-vault instead of setting them in the environment variable.

Then, we want to access them through the APIs in our code.

I am very new to the azure key vault and wanted to know if it's possible or not? A simple example/reference would help a lot.

Upvotes: 1

Views: 1707

Answers (2)

Alex Ghiondea - MSFT
Alex Ghiondea - MSFT

Reputation: 3380

Azure KeyVault has client libraries you can use to interact with KeyVault from your application.

For instance, these are the client libraries to interact with KeyVault Secrets in .NET, Java, Python and TypeScript

Here is how you can retrieve a secret from KeyVault using .NET:

// Environment variable with the Key Vault endpoint.
string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

// create the client to interact with the service
var client = new SecretClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

KeyVaultSecret secretWithValue = await client.GetSecretAsync("mySecret");
Console.WriteLine(secretWithValut.Value);

For more details, check out the samples page on the .NET repo.

Upvotes: 1

Joy Wang
Joy Wang

Reputation: 42133

It is possible, just store them in the azure keyvault and access them via the VM MSI(VM system-assigned managed identity).

Reference - Use a Windows VM system-assigned managed identity to access Azure Key Vault

Done the Prerequisites and grant the access for the MSI, in the VM, you can get the token and use the token to get the secret.

See the powershell sample below, you can also use other languages, the logic is the same, it depends on your requirement.

$response = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fvault.azure.net' -Method GET -Headers @{Metadata="true"}     
$content = $response.Content | ConvertFrom-Json     
$KeyVaultToken = $content.access_token     
(Invoke-WebRequest -Uri https://<your-key-vault-URL>/secrets/<secret-name>?api-version=2016-10-01 -Method GET -Headers @{Authorization="Bearer $KeyVaultToken"}).content 

Response:

{"value":"p@ssw0rd!","id":"https://mytestkeyvault.vault.azure.net/secrets/MyTestSecret/7c2204c6093c4d859bc5b9eff8f29050","attributes":{"enabled":true,"created":1505088747,"updated":1505088747,"recoveryLevel":"Purgeable"}} 

Update:

You need to add your VM MSI to the Access Policies of the keyvault.

enter image description here

Upvotes: 2

Related Questions