Yatrix
Yatrix

Reputation: 13775

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.

Upvotes: 20

Views: 24949

Answers (3)

tometchy
tometchy

Reputation: 710

If you need a secret variable Microsoft has prepared a manual for that as well, in an essence:

- bash: |
    echo "##vso[task.setvariable variable=mySecretVal;issecret=true]secretvalue"
- bash: |
    echo $(mySecretVal)

Upvotes: 0

Arie Laxed
Arie Laxed

Reputation: 123

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.

Upvotes: 7

Andy E
Andy E

Reputation: 538

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.

Upvotes: 11

Related Questions