ln9187
ln9187

Reputation: 740

Access Secret Variables in Visual Studio

I'm using Team Services to store sensitive data instead of hardcoding it in my code.

Let's say I defined: my_secret as name and 12345 as value in Varibles

How do I access that variable in my code?

enter image description here

In the example above, how do I access password in my code?

There is a documentation here but they don't mention it how to use the variable in the code.

Upvotes: 4

Views: 1823

Answers (3)

Stuart
Stuart

Reputation: 5496

Variables are usually passed to the build as environment variables. However secrets are not by default, you can use them explicitly in arguments to your tool like MyTool.exe $(password).

Upvotes: 1

Luca Cappa
Luca Cappa

Reputation: 1999

If you want to access the secret variables during a build step (e.g. in your custom build task PowerShell based), usually you would use that secret variable as the input argument of a task, then use the VSTS Task SDK's function Get-VstsInput like it follows:

$pwd = Get-VstsInput -Name "Input_Name_In_Task.json_File"

Then you could convert it to a SecureString as follows

$securePwd = ConvertTo-SecureString $pwd -AsPlainText -Force

and eventually use it in a new System.Management.Automation.PSCredential object.

Upvotes: 1

Daniel Mann
Daniel Mann

Reputation: 59018

It depends on what you mean by "from the code". If you're, say, invoking a script, you can pass the secret in as an argument.

As an example, here's a build definition in JSON format.

{
  "build": [
    {
      "enabled": true,
      "continueOnError": false,
      "alwaysRun": false,
      "displayName": "PowerShell Script",
      "timeoutInMinutes": 0,
      "task": {
        "id": "e213ff0f-5d5c-4791-802d-52ea3e7be1f1",
        "versionSpec": "1.*",
        "definitionType": "task"
      },
      "inputs": {
        "scriptType": "inlineScript",
        "scriptName": "",
        "arguments": "-Baz $(Baz)",
        "inlineScript": "param($Baz)\nWrite-Host \"1\" \nWrite-Host \"$($env:Foo)\" \nWrite-Host \"2\" \nWrite-Host \"$($env:Baz)\"\nWrite-Host $Baz",
        "workingFolder": "",
        "failOnStandardError": "true"
      }
    }
  ],
  "variables": {
    "foo": {
      "value": "bar"
    },
    "baz": {
      "value": null,
      "isSecret": true
    }
  }
}

Upvotes: 0

Related Questions