Mike Monteith
Mike Monteith

Reputation: 541

How can I use a secret variable in Azure Devops bash task which could be undefined

I am trying to create a config file using a bash task in Azure Devops. The variables come from azure keyvault, so I don't know which variables are defined and which ones are undefined.

- script: |
    touch config.txt
    echo "1. $(MyDefinedVariable)" >> config.txt
    echo "2. $(MyUndefinedVariable)" >> config.txt
    cat config.txt

Since MyUndefinedVariable is not defined, the pipeline doesn't substitute $(MyUndefinedVariable), resulting in a bash error MyUndefinedVariable: command not found.

I have tried using the env argument to use bash variables but I get the same error since "$(MyUndefinedVariable)" is being passed in to the bash environment.

- script: |
    touch config.txt
    echo "1. $MY_DEFINED_VARIABLE" >> config.txt
    echo "2. $MY_UNDEFINED_VARIABLE" >> config.txt
    cat config.txt
  env:
    MY_DEFINED_VARIABLE: $(MyDefinedVariable)
    MY_UNDEFINED_VARIABLE: $(MyUndefinedVariable)

I just want undefined variables to resolve to an empty string but can't find a sensible way to do it.

Upvotes: 3

Views: 3771

Answers (1)

Krzysztof Madej
Krzysztof Madej

Reputation: 40929

All variables mapped from Azure KeyVault are considered as secrets so mapping like this one is necessary:

  env:
    MY_DEFINED_VARIABLE: $(MyDefinedVariable)
    MY_UNDEFINED_VARIABLE: $(MyUndefinedVariable)

I'm afraid that if you are not aware of values in your KeyVault you need to use Azure CLI to check this. To checks all secret keys you can use this command:

az keyvault secret list [--id]
                        [--maxresults]
                        [--query-examples]
                        [--subscription]
                        [--vault-name]

You can combine this CLI with Azure CLI task.

Upvotes: 5

Related Questions