Using a variable in GitLab CICD pipeline rules clause - gitlab

In my GitLab CICD pipeline I've defined a job with the following rule:
rules:
- if: $TERRAFORM_ENVIRONMENT == "qa" && $TERRAFORM_EXCLUDED_ENVIRONMENTS !~ /qa/
Each job has an environment clause and its name defined.
This allows me to target the pipeline to execute when TERRAFORM_ENVIRONMENT is set to "qa" while ensuring "qa" environment isn't part of TERRAFORM_EXCLUDED_ENVIRONMENTS list.
The value of TERRAFORM_EXCLUDED_ENVIRONMENTS variable is a series of comma separated environment names as a single string, for example, "dev,qa,uat".
While this rule works, I want to make the pipeline more maintainable across multiple environments without having to explicitly state the environment name. I want to be able to use $CI_ENVIRONMENT_NAME instead.
This is what I want to do:
rules:
- if: $TERRAFORM_ENVIRONMENT == "$CI_ENVIRONMENT_NAME" && $TERRAFORM_EXCLUDED_ENVIRONMENTS !~ /$CI_ENVIRONMENT_NAME/
When I tried this in my CICD pipeline, the job was executed even though "qa" was part of $TERRAFORM_EXCLUDED_ENVIRONMENTS.
Does anyone know how I can get this to work?

Related

Trigger Gitlab-CI Pipeline only when there is a new tag, with some rules

in the answer of this (Trigger Gitlab-CI Pipeline only when there is a new tag ), I understand to set only as filter
But How can I trigger the pipeline only:
there is a new tag created, these tags are semantic versioning tags, how can I filter them? something like
only:
- /[0-9]+\.[0-9]+\.[0-9]+/
but the tags are not always as 1.0.2, sometimes, they have beta or fc, such as 0.2.3-rc.1 or 2.3.5-beta, will the filter to be /[0-9]+\.[0-9]+\.[0-9]+.*/ is fine?
second rule is, the trigger is only on master or main branch
Regarding the Semantic versioning regex, I found this gist
https://gist.github.com/jhorsman/62eeea161a13b80e39f5249281e17c39
the sample is too complex
^([0-9]+)\.([0-9]+)\.([0-9]+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+)?$
Using only is deprecated in favor of rules.
rules replaces only/except and they can’t be used together in the same job.
https://docs.gitlab.com/ee/ci/yaml/#rules
Create a rule and check the predefined variable CI_COMMIT_TAG for your pattern.
job:
script: echo "Hello, Rules!"
rules:
- if: $CI_COMMIT_TAG =~ /^\d+\.\d+\.\d+.*/
You can list multiple of these rules. So if you want to execute the job also on every push to the master branch, you'd add another rule:
rules:
- if: ...
- if: $CI_COMMIT_REF_NAME == "master"
The extended pattern with .* at the end would be fine, but you could also be a bit more specific like this (-[0-9a-zA-Z.]+)? if you want to enforce a specific syntax.

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'

How to exclude tags with patterns in gitlab ci config

I have a gitlab repo and I am trying to create some tags on top of required commits. But my CICD library (included) is having a job (job1) in a stage which runs on every tag/branch/commit. I want to exclude it to run on particular formats of tags. (eg. pre_final-2.3.1).
I tried giving the tag pattern in my .gitlab-ci.yaml in the except section of the job as below.
Eg:
job1:
except:
- ^pre_final-\d+\.\d+\.\d+$
It is still adding the job job1 to the pipeline for the CICD builds running on this tag. I believe this pattern is checking with branch name. But is there a way to mention the ref we provide in the except section is branch or tag?
Ref: https://docs.gitlab.com/ee/ci/yaml/#onlyrefs--exceptrefs
You should rules instead as only/except is not developed further. There you can check for the the name of your tag.
job1:
rules:
- if: '$CI_COMMIT_TAG =~ /^pre_final-\d+\.\d+\.\d+$/'
when: never
- when: always
There is no separate classification as branch or tag while using them in only/except.
I realized that I am giving a wrong regex pattern and thus it is not working for the tag pattern I am trying for
^pre_final-\d+\.\d+\.\d+$ --> /^pre_final-\d+\.\d+\.\d+$/
So my .gitlab-ci.yaml contains as below
job1:
except:
# matches with branch or tags names
- /^pre_final-\d+\.\d+\.\d+$/
Since above usage matches both branch and tag names, if we want to match only branch name or match only tag name, then we can use the below format
job1:
except:
variables:
# to match only tag names
- $CI_COMMIT_TAG == /^pre_final-\d+\.\d+\.\d+$/
# to match only branch names
- $CI_COMMIT_BRANCH = /^pre_final-\d+\.\d+\.\d+$/

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