Azure Pipeline: Variable expansion in depends statement - azure

I struggle with setting up a condition statement to run a specific task only on main and when there is a CI build.
While trying without success, I came across this statement which is an AND of two exactly the same statements:
condition: and(contains(variables['build.sourceBranch'], 'refs/heads/main'), contains(variables['build.sourceBranch'], 'refs/heads/main'))
When running it on my branch, I see this result:
Evaluating: and(contains(variables['build.sourceBranch'], 'refs/heads/main'), contains(variables['build.sourceBranch'], 'refs/heads/main'))
Expanded: and(contains('refs/heads/task/mybranch', 'refs/heads/main'), contains(variables['build.sourceBranch'], 'refs/heads/main'))
Result: False
Why is the second variable not expanded?
To reach my aim of that condition, I'd like to run something like this, but here the expansion does not work as well:
and(endsWith(variables['build.sourceBranch'], 'refs/heads/main'), endsWith(variables['build.reason'], 'CI'))
What am I doing wrong?
Thanks in advance

Related

gitlab branch common name - pipeline should be run execpt none branch should not be run

I want to run pipeline specific branches in GitLab like the branch names are sprint_100, Sprint-1,SPRINT-202.
How should I give commands in rules?
(/^SPRINT_[0-9]+\.[0-9]+$/)||(/^Sprint_[0-9]+\.[0-9]+$/)||(/^Sprint_[0-9]+\.[0-9]+$/)
I used this, but it doesn't work. Kindly help me to sort it out this. Thank you!
This rules clause should work for your example to run a pipeline only branch names like sprint_100, Sprint-1 or SPRINT-202.
The regex will match case-insensitive on branch names starting with 'sprint' followed by either '-' or '_' and an unlimited amount of digits.
I am no regex expert so this regex can likely be improved.
rules:
- if: '$CI_COMMIT_BRANCH =~ /^SPRINT[-_][0-9]+/i'

Azure Canary Deployment - Use variable for increments

We are using a canary deployment job in Azure. The job is defined in a template. We want to set the "increments:" parameter at runtime to a single value (i.e. [ 50 ] rather than [ 25, 50 ]). The value is an output of a prior job. I've tried a few different approaches and receive various errors immediately in the screen where one tries to start the pipeline, before it actually starts.
Simplified yaml:
jobs:
- job: preValidationCanary
steps:
- task: PythonScript#0
name: setCanaryDeploymentVariables
script: |
# Do stuff to determine percentage
print("##vso[task.setvariable variable=%s;isOutput=true]%s" % ("deploy_canaryTrafficSplitPercentage_global", trafficPercentageInt ))
- deployment: deployCanary
dependsOn:
- preValidationCanary
variables:
deploy_canaryTrafficSplitPercentage: $[ dependencies.preValidationCanary.outputs['setCanaryDeploymentVariables.deploy_canaryTrafficSplitPercentage_global'] ]
strategy:
canary:
increments: $[deploy_canaryTrafficSplitPercentage]
I've tried passing just the number from the prior job, and then using this syntax:
increments: [ $[deploy_canaryTrafficSplitPercentage] ]
This results in the error: "While parsing a flow sequence, did not find expected ',' or ']'."
I've tried using the macro syntax:
increments: [ $(deploy_canaryTrafficSplitPercentage) ]
This results in the error: "Mapping values are not allowed in this context."
In case there was an issue expanding a number into the brackets, I tried passing a string from the prior job, using the runtime syntax:
- task: PythonScript#0
name: setCanaryDeploymentVariables
script: |
# Do stuff to determine percentage
print("##vso[task.setvariable variable=%s;isOutput=true]%s" % ("deploy_canaryTrafficSplitPercentage_global", str(trafficPercentageInt) ))
This also provided the error: "While parsing a flow sequence, did not find expected ',' or ']'."
So I tried this with macro syntax, which provided the error: "Mapping values are not allowed in this context."
I'll continue to beat my head against this, but if anyone either knows how this can be done, or knows that it cannot be done, please reply.

Gitlab download artifact of matrix job

I am trying to download artifacts from a successful job.
The download for a regular job works but the download of of a job matrix is not working.
Any idea how I have to structure the URL for that.
lambda_build: [tools]
lambda_build: [helper]
lambda-master works with ..../-/jobs/artifacts/master/download?job=lambda-master
I don't find answer in the gitlab documentation.
Executing a matrix job generates a name unique to that pipeline from each variable used, so I think you can't just use the name you gave the job alone.
For example, when declaring this matrix job:
myJob:
script: echo $FOO
parallel:
matrix:
- FOO: [bar, baz]
Gitlab will generate two jobs:
myJob: [bar]
myJob: [baz]
So you might have to put "build: [$lambda_build]" or something into the query parameter.

Gitlab only: variables multiple

is there anyway to do multiple AND variable expression?
let's say
.template1:
only:
variables:
- $flag1 == "true"
.template2:
only:
variables:
- $flag2 == "true"
job1:
extends:
- .template1
- .template2
script: echo "something"
How will this get evaluated?
Is this going to result in only:variables overwriting each other thus template2 is the final result?
or is this going to result in a combined variables such that it becomes an OR statement
only:
variables:
- $flag1 == "true"
- $flag2 == "true"
Is there anyway to make it as and AND statement instead? keeping the templating system, and without using rules: if since using rules if has its own quirk, triggering multiple pipeline during merge request
Problem
Any time two jobs get "merged", either using extends or anchors, GitLab will overwrite one section with another. The sections don't actually get merged. In your case, you're extending from two jobs, so GitLab will completely overwrite the first variables section with the second.
Solution
One way to achieve your desired result is by defining the variables in your template jobs. The problem you will have then is the two variables sections will overwrite each other. So..
You can use a before_script section to define the variable in the 2nd template. This approach works for your specific case of 2 templates. You can use script and after_script if you need a third template, buy you'd have to use a more advanced approach if you need more templates than that.
.template1:
# We can define a variables section here, no problem
variables:
flag1: "true"
.template2:
# You can't define a second variables section here, since it will overwrite the first
# Instead, define the environment variable directly in a before-script section
before_script:
- export flag2="true"
job1:
extends:
- .template1
- .template2
only:
variables:
- $flag1 == "true"
- $flag2 == "true"
script: echo "something"

Howto: Dynamic variable name resolution in Azure DevOps YAML

The consistency of Variable support & the syntax vary wildly in Azure DevOps YAML.
Case in point:
trigger:
- master
# Variable Group has $(testCategory1) with value
# 'TestCategory=bvttestonly | TestCategory=logintest'
variables:
- group: DYNAMIC_VG
jobs:
- job:
pool: 'MyPool' #Has about 10+ self hosted agents
strategy:
parallel: $[ variables['noOfVMsDynamic']]
variables:
indyx: '$(testCategories$(System.JobPositionInPhase))'
indyx2: $[ variables['indyx'] ]
testCategories: $[ variables[ 'indyx2' ] ]
steps:
- script: |
echo "indyx2 - $(indyx2)"
echo "testCategories $(testCategories)"
displayName: 'Display Test Categories'
The step prints:
"indyx2 - $(testCategories1)"
"testCategories $(testCategories1)"
I need to print the value of $(testCategories1) defined in the Variable Group:
'TestCategory=bvttestonly | TestCategory=logintest'
This may work to you:
variables
indyx: $[ variables[format('{0}{1}', 'testCategories', variables['System.JobPositionInPhase'])] ]
It worked for me, in a slightly different situation which also required some dynamic variable names.
Howto: Dynamically resolve a nested variable in Azure DevOps YAML
That because the value of nested variables (like $(testCategories$(System.JobPositionInPhase))) are not yet supported in the build pipelines at this moment.
That the reason why you always get the value $(testCategories1) rather than the real value of variable testCategories1.
I encountered this issue many times in my past posts and we do not have a perfect solution before Azure Devops supports this feature.
For the convenience of testing, I simplified your yaml like following:
jobs:
- job: ExecCRJob
timeoutInMinutes: 800
pool:
name: MyPrivateAgent
displayName: 'Execute CR'
variables:
testCategories1: 123456
testCategoriesSubscripted: $(testCategories$(System.JobPositionInPhase))
strategy:
parallel: $[variables['noOfVMs']]
steps:
- template: execute-cr.yml
parameters:
testCategories: $(testCategoriesSubscripted)
The execute-cr.yml:
steps:
- script: echo ${{ parameters.testCategories }}
We always get the $(testCategories1)NOT the value of it.
If I change the $(testCategories$(System.JobPositionInPhase)) to $(testCategories1), everything work fine.
Since nested variables are not yet supported, As workaround, we need to expand the nested variables for each value of testCategories, like:
- job: B
condition: and(succeeded(), eq(dependencies.A.outputs['printvar.skipsubsequent'], 'Value1'))
dependsOn: A
steps:
- script: echo hello from B
Check the Expressions Dependencies for some more details.
Hope this helps.
If I'm understanding your issue correctly, the problem is that the pipeline evaluates all variables at the runtime of the job. The solution in this scenario is to split your tasks into separate jobs with dependencies.
Have a look at my answer in this post and let me know if it's what you're after : YAML pipeline - Set variable and use in expression for template
I manage to get dynamic name resolution by using get-item to read the corresponding environment variable, allowing construction of the name of the variable and then getting the value.
In our case we save the name of an autogenerated branch into a variable group and each repository will have its own variable.
$branchVarName = "$(Build.Repository.Name).BranchName".replace(".","_")
$branchName = (get-item -Path Env:$branchVarName).value
write-host "/$(System.TeamProject)/_apis/build/builds?&repositoryId=$(Build.Repository.ID)&repositoryType=TFSGit&branchName=refs/heads/$branchName&api-version=6.0"
Notice in the second line that I reference the variable content using .value because get-item returns a name/value key pair.
This extraction has to be done in script but could be exposed as an output variable if needed in another context.

Resources