DEV Community

Cover image for Store your automation credentials in Azure KeyVault

Posted on

Store your automation credentials in Azure KeyVault

There's a common problem storing login credentials for automation that runs in Production or near-Production (aka Stage), where do you store them? You really shouldn't check them into source code! I guess that you could encrypt them somehow but a better solution is to store them in Azure KeyVault and pull them out when you need them. So how can you do this? The Microsoft documentation on how to do this is fairly confusing so I'll give you a step by step approach.

1) In Azure create a new KeyVault for your test credentials and create a couple of secrets that represent a username and password.


2) In Azure create a new Managed Identity that you will use for Automation. Note the ClientId value for future use.


3) In your new KeyVault under Access Policies add the Managed Identity and grant it privileges.


4) Ok time to write code! I wrote a XUnit test to verify that I could pull the secrets

[Trait("Category", "AuthTest")]
public async Task GetKeyVaultCreds()
    // Define all of your variables
    string keyVaultUrl = "";
    string secretName = "TestAutomationUserHAP";
    string secretPassword = "TestAutomationPasswordHAP";

    // Specify the Azure ClientId of the Managed Identity you created
    string userAssignedClientId = "********-****-****-****-************";

    // Specify the Azure TenantId of the KeyVault you are accessing
    const string tenantId = "********-****-****-****-************";
Environment.SetEnvironmentVariable("AZURE_TENANT_ID", tenantId);

    // Create Azure credential using the managed identity
    var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions { ManagedIdentityClientId = userAssignedClientId });

    // Create an Azure SecretClient object
    var client = new SecretClient(new Uri(keyVaultUrl), credential);

    // Get those secrets!
    var secretUser = await client.GetSecretAsync(secretName).ConfigureAwait(false);
    var secretPass = await client.GetSecretAsync(secretPassword).ConfigureAwait(false);
Enter fullscreen mode Exit fullscreen mode

Now you can grab username and passwords from Azure that you need for your automation. Just convert the test above to a helper method. Cheers!

Top comments (2)

anoopsimon profile image
Anoop Simon

Good one !

But storing ClientId,TenantId,ClientSecret Id etc. in code is also not always safe. Please make sure to put them in your pipeline (azure DevOps/Jenkins etc.) configuration , and let the pipeline manage them for you.

Authenticate KeyVault via Azure CLI For development and debugging purposes so there is no need to store client/tenant/secret ids in code at all

tswiftma profile image

Good point, I have stored other variables in my pipelines!