Created
February 7, 2023 18:54
-
-
Save rfennell/6edb0ea400f23fdeb0c188b4011caf29 to your computer and use it in GitHub Desktop.
An inline task to convert a regex based filter to a comma separated list as required to download Secrets from KeyVault in Azure DevOps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
variables: | |
# the variable used to filter the KeyVault secret list | |
# This can be a simple prefix and wildcard e.g. 'Config-*'' | |
# Or a more complex regex expression e.g. ^(?:Config-*|Settings-*) | |
- name: KV-Filter | |
value: '^(?:Config-*|Settings-*)' | |
# the variable used to KeyVault name | |
- name: KV-Name | |
value: 'bm-kv1' | |
stages: | |
- stage: Private | |
jobs: | |
- job: Test | |
pool: | |
vmImage: windows-latest | |
steps: | |
- task: AzurePowerShell@4 | |
displayName: 'Get filtered list of secret name from Azure Key Vault' | |
inputs: | |
azureSubscription: 'RF Black Marble Subscription (keyvaultsp)' | |
ScriptType: 'InlineScript' | |
Inline: | | |
# Check we have no parameter, or the generic wildcard, if true return the default | |
if ([string]::IsNullOrEmpty('$(KV-Filter)') -or '$(KV-Filter)' -eq '*') { | |
write-host "No filter passed for the KeyVault, so setting the filter list to the wildcard: *" | |
$list = "*" | |
} else { | |
write-host "Getting secrets in Key Vault $(KV-Name) that match provided the filter: $(KV-Filter)" | |
$secrets = Get-AzKeyVaultSecret -VaultName $(KV-Name) | where-object { $_.name -match ('$(KV-Filter)') -and $_.enabled -eq $true } | |
write-host "Found $($secrets.count) matching secrets" | |
# list the secret names | |
$secrets | select name | |
# create the comma separated list | |
$list = $secrets.name -join ',' | |
} | |
# set a variable available to other tasks in this job in the form $(FILTERED_SECRETNAMES) | |
Write-Host "##vso[task.setvariable variable=FILTERED_SECRETNAMES]$list" | |
azurePowerShellVersion: 'LatestVersion' | |
- task: AzureKeyVault@1 | |
displayName: 'Get secrets from Azure Key Vault' | |
inputs: | |
azureSubscription: 'RF Black Marble Subscription (keyvaultsp)' | |
KeyVaultName: 'bm-kv1' | |
SecretsFilter: $(FILTERED_SECRETNAMES) | |
RunAsPreJob: false # cannot be run as prejob as the variable from the previous script will not be evaluated | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment