Search code examples
azure-devopsazure-pipelinesazure-pipelines-yaml

Azure DevOps: Error when secret contains double and single quotes


I read from the Azure Key Vault a secret as follows and want to pass the content as an output variable.

  - task: AzureKeyVault@2
    inputs:
      azureSubscription: 'Azure'
      KeyVaultName: 'kv'
      SecretsFilter: 'XXX'
      RunAsPreJob: false

  - task: CmdLine@2
    inputs:
      script: 'echo $(XXX)'

  - bash: |
      WI=$(DB-WORKSPACE-INFO)
      echo "##vso[task.setvariable variable=testvar;isOutput=true;]$WI"

The problem is, that the key contains ' as well as " and so I get

unexpected EOF while looking for matching `"'

How can I handle that?

EDIT Based on @Jessehouwing suggestion I changed the script to

  - bash: |
      echo '##vso[task.setvariable variable=testvar;isOutput=true;]$SECRET_VALUE'
    env:
      SECRET_VALUE: $(XXX)
    name: step    

Now, I do not get any error but $SECRET_VALUE seems not to be resolved. In the following step, where I get the output variable the content of testvar is $SECRET_VALUE


Solution

  • Right now you're using the inlining syntax to put the content of the secret directly in the script file, this requires the resulting script to be syntactically correct, and as you've figured out can cause interesting issues.

    This is also a potential security issue, as people could also add a command to sent your secret by curl to a remote host for example.

    It's therefore safer to pass secrets as an environment variable:

     - script: |
           echo "%MY_SECRET_VALUE%"
       env:
         MY_SECRET_VALUE: $(XXX)
    
     - bash: |
           echo "$MY_SECRET_VALUE"
       env:
         MY_SECRET_VALUE: $(XXX)
    

    This has the added benefit that the secret itself isn't written to disk as part of the temporary script file. And it protect you against script injection attacks.

    This is a better approach in general in the scripts, relying on the automatic environment variables for normal variables and explicit environment variables for secrets and more complex variable expressions.

    Almost every task supports the extra env: section.

    For bash, make sure you use " around the string you pass to echo, otherwise variables aren't expanded.