Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a build variable in Azure DevOps with Bash?

I'm using the below to pull the version from my package.json file and set it to one of my build variables, Version.

# successfully retrieves and prints the version to console
ver=$(node -e "console.log(require('./package.json').version)")
echo "Version: $ver"

# does jack squat
# even trying to hard-code something in place of $ver doesn't set the variable
echo "##vso[task.setvariable variable=Version]$ver"
echo "Version: $(Version)"

I've tried using ver and $(ver) instead of $ver, none work as the console prints a blank for $(Version) in all cases (it's empty to begin with). If I hard-code Version, it prints fine, so it's not the printing or the retrieving, it's the setting that's the issue. I've based my script on MS' example,

echo "##vso[task.setvariable variable=sauce]crushed tomatoes"

Our build server is in a Windows environment.

like image 280
Yatrix Avatar asked Dec 18 '18 16:12

Yatrix


People also ask

How do I set an Environment variable in Azure?

To set environment variables when you start a container in the Azure portal, specify them in the Advanced page when you create the container. Under Environment variables, enter NumWords with a value of 5 for the first variable, and enter MinLength with a value of 8 for the second variable.


2 Answers

coming at this a while after posting, but thought I'd share just in case others stumble upon this.

From the documentation, the pipeline variable doesn't get expanded until after the task is over. Microsoft has enhanced their documentation to illustrate it better

steps:

# Create a variable
- script: |
    echo '##vso[task.setvariable variable=sauce]crushed tomatoes'

# Use the variable
# "$(sauce)" is replaced by the contents of the `sauce` variable by Azure Pipelines
# before handing the body of the script to the shell.
- script: |
    echo my pipeline variable is $(sauce)

I suspect that is why even when hard coding a value, you weren't seeing anything still.

like image 112
Andy E Avatar answered Sep 21 '22 19:09

Andy E


After this line echo "##vso[task.setvariable variable=Version]$ver" the value is stored in an environment variable VERSION.

You can access it in a next script-step, using:

- bash: |
    echo "my environment variable is $VERSION"
- pwsh: |
    Write-Host "my environment variable is $env:VERSION"
- script: |
    echo "my environment variable is %VERSION%"

You could then use PowerShell to turn it in a pipeline variable:

- pwsh: |
    Write-Host "Setting version to: $env:VERSION"
    Write-Host "##vso[task.setvariable variable=version;isOutput=true]$env:VERSION"
  displayName: 'Set version'
  name: set_version

After that you can use $(set_version.version) in other tasks or parameters.

like image 24
Arie Laxed Avatar answered Sep 18 '22 19:09

Arie Laxed