Richard Barraclough
Richard Barraclough

Reputation: 2964

Azure pipeline: make secret variable into environment variable

I need to get the value of a secret variable into an environment variable because some idiot wrote unit tests that connect to a database and the connection string is an environment variale (and didn't do any dependency injection so it can't be replaced).

Here's the code that gets the connection string

return Environment.GetEnvironmentVariable("AZ_Db_Secret");

These steps don't work

name: $(Build.BuildId)-${{ variables['Build.SourceBranchName']}}

pool:
  vmImage: 'windows-latest'

variables:
  System.Debug: true
  AZ_Db_Secret: $(AzDbConnectionString) 

steps:
- task: PowerShell@2
  displayName: Set environment variable from AzDbConnectionString
  inputs:
    targetType: 'inline'
    script: |
      [Environment]::SetEnvironmentVariable("AZ_Db_Secret", $env:DB_CS, "User")
      echo "------------------------"
      echo $env:DB_CS
      echo $env:AZ_Db_Secret
      echo "------------------------"
  env: 
    DB_CS: $(AzDbConnectionString)

- task: PowerShell@2
  displayName: x1
  inputs:
    targetType: 'inline'
    script: |
      echo "------------------------"
      echo $env:DB_CS
      echo $env:AZ_Db_Secret
      echo "------------------------"

The first task outputs

------------------------
***
------------------------

The second task outputs

------------------------
------------------------

showing that the environment variable has not been set.

How can I get it to set the environment variable?

Should I just hard code the connection string into the yml?

Upvotes: 0

Views: 812

Answers (1)

rudymiked
rudymiked

Reputation: 33

OK! I was having the same problem and I finally got this to work:

enter image description here

So the environment variable didn't carry over to the dotnet test task in the pipeline, but if you declare the variable in a Powershell task and run the test manually, then the environment variable is available!

$(yoursecret) is from the Azure Key Vault, set up that task normally with "*" as the secrets filter.

Upvotes: 1

Related Questions