How to pass KeyVault secrets to a template or a script file in Azure Pipelines?

Viewed 63

I have this YAML file:

  steps:
      - task: AzureKeyVault@2
        displayName: Get secret from AzureVault
        inputs:
            azureSubscription: 'subName'
            KeyVaultName: 'vaultName'
            SecretsFilter: 'mySecret'
            RunAsPreJob: true

      - template: \pipelines\templates\vm_setup.yml
        parameters:
            os_pass: $(mySecret)

How do I use mySecret inside myScript.ps1 or inside myTemplate.yml? I tried to pass it as an argument, or map it to an env variable then pass that env variable as an argument but neither worked!

My myTemplate.yml looks like this:

parameters:
    - name: os_pass
      type: string

steps:

- task: PowerShell@2
  displayName: Trial
  inputs:
      targetType: 'filepath'
      filePath: '${{ parameters.workingDirectory }}\myScript.ps1'
      arguments: >-
          - OS_Pass ${{ parameters.os_pass }}

And this is myScript.ps1

param (
    [Parameter(Mandatory = $true)]
    [string]$OS_Pass
)

$password = ConvertTo-SecureString -String $OS_Pass -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList 'admin', $password

Write-Host '---------'
Write-Host $OS_Pass

Doing so the secret is now a string! How do I pass it without changing its type?

1 Answers
Related