Quick Tip: Accessing a Azure DevOps secret from within a scripted step

Published by

In today’s quick tip, we are going to see how we can access a secret that we’ve defined in a variable group as part of a Azure DevOps yml based build.

By design, any variable from a linked variable set will:

  • Be hidden from logs; and
  • Not be placed in as an environment variable

In the blog posts that I’ve seen to date, they’ve mentioned about using the ##vso[task.setvariable name]value command inside of a script. I personally dislike this way as it clutters the build with extra steps that I feel are unnecessary and it makes it harder to find when looking at the configuration file. You may still have to use this approach when the following tip does not work.

In order to pull in a value from a variable group, you must link the variables by using the following snippet:

variables:
- group: MY_VARIABLE_GROUP_NAME

Replace MY_VARIABLE_GROUP_NAME with your variable group name.

Multiple groups can be added like so:

variables:
- group: MY_VARIABLE_GROUP_NAME
- group: MY_VARIABLE_GROUP_NAME_2

And then in the steps, and the env: section linking the SECRET_TOKEN variable as follows:

steps:
- script: 'echo Your script here'
displayName: 'My Test Script'
env:
    SECRET_TOKEN: $(SECRET_TOKEN)

Replace SECRET_TOKEN with the name of your variable that you wish to access.

That’s it. From now you should be able to access your secret variables from within your scripts and not have them written out to logs.

Further Reading