powershellazure-devopsazure-pipelinesazure-keyvaultazure-pipelines-yaml

How to access secure variable in condition property of Powershell task in Azure pipeline


I access a secret value using AzureKeyVault@2 in a step prior then use PowerShell@2 command to execute a PowerShell script. I want to execute this step conditionally.

Here is a variable (key) I fetch a secret from Key Vault. This a variable beacuse, It will vary depending on environment.

variables:
  DefaultConnection : 'dynamic-key-dev'

I'm able to retrieve the secret using

- task: AzureKeyVault@2
   inputs:
    azureSubscription: 'Azure Key Vault Service Connection'
    KeyVaultName: 'kv-example-kv'
    SecretsFilter: ${{ variables.DefaultConnection }}
    RunAsPreJob: false

Now I want to conditionally execute the next step provided the secret contains specific keywords

- task: PowerShell@2
  condition: contains("$env:MY_MAPPED_SEC"), 'must-contain')
  continueOnError: true
  inputs:
    targetType: 'inline'
    script: |
      echo "Do Something with $env:MY_MAPPED_SEC"
    env:
      MY_MAPPED_SEC: $(${{ variables.DefaultConnection }})

condition fails to evaluate to true, Without condition, I have verified that $env:MY_MAPPED_SEC is mapped and retrieved correctly from KV.


Solution

  • Conditions are evaluated to determine whether to start a stage, job, or step. Therefore, nothing computed at runtime inside that unit of work is available.

    In other words, giving that the environment variable MY_MAPPED_SEC is set inside the PowerShell@2 task, it cannot be used as condition for the task itself.

    So instead of:

    - task: PowerShell@2
      condition: contains("$env:MY_MAPPED_SEC"), 'must-contain')
      # ...
    

    Try something like (not tested):

    - task: PowerShell@2
      condition: contains(variables['${{ variables.DefaultConnection }}'], 'must-contain')
      # ...