Passing Storage Account Secret Key Dynamically in Azure DevOps Pipelines

·

2 min read

Cover Image for Passing Storage Account Secret Key Dynamically in Azure DevOps Pipelines

Managing secrets securely is a critical aspect of cloud and DevOps practices. When working with Azure Storage Accounts, you might need to dynamically pass the secret key to scripts or tasks. In this article, I will explain how to achieve this using Azure CLI, PowerShell, and the Replace Tokens task in Azure DevOps.

In this article, I will deploy Terraform resources using Azure DevOps. Please find the code in below repo

Code repo for this project

Define Variables

To begin, we need to create a variable called storagekey. The value of this variable will be empty initially and will be dynamically fetched by the pipeline using a PowerShell script. Make sure to mark the variable as "Settable at release time."

Add Azure PowerShell script: InlineScript task

In this task, include the PowerShell script that fetches the storage account key and passes it to your pipeline.

$key = (Get-AzStorageAccountKey -ResourceGroupName $(terraformrg) -AccountName $(terraformstorageaccount))[0].Value

Write-Host "##vso[task.setvariable variable=storagekey]$key"

This script retrieves the storage account key dynamically and stores it in the pipeline variable storagekey.

Replace Tokens Task

The Replace Tokens task allows you to dynamically replace placeholders in your code with pipeline variables. Follow these steps:

  1. Specify Source Code and Target Files:

    • In the task configuration, define the source code directory and the target files where the placeholders need to be replaced.
  2. Set Prefix and Suffix:

    • Use the same prefix and suffix as defined in your code. For example, if your placeholders look like __storagekey__, set the prefix to and the suffix to __.

When the pipeline runs, the Replace Tokens task will substitute the placeholders in the target files with the values of the corresponding pipeline variables.

Why This Approach Works

By dynamically fetching the storage account secret key and passing it securely through the pipeline:

  • Security: Secrets are not hardcoded, reducing the risk of exposure.

  • Automation: The pipeline can handle key rotations without manual intervention.

  • Flexibility: The Replace Tokens task ensures that the updated key is seamlessly integrated into your code.


Conclusion

This method allows you to securely and dynamically manage storage account secret keys in Azure DevOps pipelines. When keys are recreated, the pipeline remains unaffected, ensuring smooth and secure operations. By following these steps, you can enhance the security and automation of your DevOps workflows.