How to pass variables between tasks in Azure DevOps pipeline using JavaScript?

I’m working on an Azure DevOps pipeline and I’m stuck. I need to set a variable in one task and use it in another task. Both tasks use JavaScript.

Here’s what I’ve tried:

In the first task, I’m doing this:

let connectionInfo = tl.getInput('connectionString', true);
if (connectionInfo) {
  let authData = tl.getEndpointAuthorization(connectionInfo, false);
  
  let secretKey = authData.parameters['secretKey'];
  let accountName = authData.parameters['accountName'];
  
  if (authData) {
    console.log('##vso[task.setvariable variable=secretKey;]', secretKey);
  }
}

Then in the second task, I’m trying to use the variable like this:

console.log(secretKey);

But I keep getting an error saying secretKey is not defined. What am I doing wrong? How can I make this work? Any help would be great!

hey joec, i’ve run into this before. the trick is to use tl.getVariable() in your second task. it’s way more reliable for grabbing variables from earlier tasks. just do something like:

const secretKey = tl.getVariable(‘secretKey’);
console.log(secretKey);

make sure your tasks run in order tho. hope this helps!

I’ve dealt with this exact scenario in my Azure DevOps projects. One trick I found that works well is using the tl.getVariable() method in your second task. It’s a more reliable way to fetch variables set in previous tasks.

Try modifying your second task like this:

const tl = require('azure-pipelines-task-lib/task');
const secretKey = tl.getVariable('secretKey');
console.log(secretKey);

This approach has consistently worked for me across different pipeline configurations. Just make sure your tasks are running in the correct order, and that you’re not accidentally overwriting the variable somewhere else in your pipeline.

Also, double-check that your first task is actually succeeding. If it fails, the variable won’t be set, which could explain why you’re not seeing it in the second task. You might want to add some error handling and logging in the first task to ensure it’s executing as expected.

I’ve encountered this issue before. The problem is that you’re trying to access the variable directly in JavaScript, which won’t work. In Azure DevOps, variables set using ‘##vso[task.setvariable]’ are environment variables, not JavaScript variables.

To access the variable in your second task, you need to use the process.env object. Try modifying your second task like this:

console.log(process.env.secretKey);

This should correctly retrieve the value you set in the first task. Remember, environment variables are always strings, so you might need to parse it if you’re expecting a different data type.

Also, ensure your second task is set to run after the first one in your pipeline definition. Variables set in one task are only available to subsequent tasks.