Set Azure DevOps Build Number to Gitversion MajorMinorPatch number - azure-devops

I am trying to set my build number for my Azure DevOps Pipeline to my MajorMinorPatch version from gitversion. I have the following in my YAML for my pipeline:
- task: GitVersion#5
inputs:
preferBundledVersion: false
updateAssemblyInfo: true
- task: PowerShell#2
inputs:
targetType: 'inline'
script: |
$versionInfo = '$($GITVERSION_MAJORMINORPATCH)'
Write-Host("##vso[task.setvariable variable=Version;]$versionInfo")
- script: echo %Action%%BuildVersion%
displayName: 'Set build version'
env:
Action: '##vso[build.updatebuildnumber]'
BuildVersion: '$env:Version'
The problem is that when I run my pipeline, I get a pipeline name like: 0.1.0-alpha.70
I am not sure why I get the -alpha.70. I know what they mean, I think, but I don't expect to see them in my string for Version. When I run gitversion locally, my MajorMinorPatch string is 0.1.0 and that is all I want to see. Can anyone help me get just that information?
EDIT: For anyone that is curious, I am including my GitVersion.yml here, it is pretty much the standard config:
assembly-versioning-scheme: MajorMinorPatch
assembly-file-versioning-scheme: MajorMinorPatchTag
mode: ContinuousDeployment
tag-prefix: '[vV]'
continuous-delivery-fallback-tag: ''
major-version-bump-message: '\+semver:\s?(breaking|major)'
minor-version-bump-message: '\+semver:\s?(feature|minor)'
patch-version-bump-message: '\+semver:\s?(fix|patch)'
no-bump-message: '\+semver:\s?(none|skip)'
legacy-semver-padding: 4
build-metadata-padding: 4
commits-since-version-source-padding: 4
commit-message-incrementing: Enabled
branches:
develop:
mode: ContinuousDeployment
tag: alpha
increment: Minor
prevent-increment-of-merged-branch-version: false
track-merge-target: true
regex: ^dev(elop)?(ment)?$
source-branches: []
tracks-release-branches: true
is-release-branch: false
is-mainline: false
pre-release-weight: 0
master:
mode: ContinuousDeployment
tag: ''
increment: Patch
prevent-increment-of-merged-branch-version: true
track-merge-target: false
regex: ^master$
source-branches:
- develop
- release
tracks-release-branches: false
is-release-branch: false
is-mainline: true
pre-release-weight: 55000
release:
mode: ContinuousDeployment
tag: beta
increment: None
prevent-increment-of-merged-branch-version: true
track-merge-target: false
regex: ^releases?[/-]
source-branches:
- develop
- master
- support
- release
tracks-release-branches: false
is-release-branch: true
is-mainline: false
pre-release-weight: 30000
feature:
mode: ContinuousDeployment
tag: useBranchName
increment: Inherit
prevent-increment-of-merged-branch-version: false
track-merge-target: false
regex: ^features?[/-]
source-branches:
- develop
- master
- release
- feature
- support
- hotfix
tracks-release-branches: false
is-release-branch: false
is-mainline: false
pre-release-weight: 30000
pull-request:
mode: ContinuousDeployment
tag: PullRequest
increment: Inherit
prevent-increment-of-merged-branch-version: false
tag-number-pattern: '[/-](?<number>\d+)'
track-merge-target: false
regex: ^(pull|pull\-requests|pr)[/-]
source-branches:
- develop
- master
- release
- feature
- support
- hotfix
tracks-release-branches: false
is-release-branch: false
is-mainline: false
pre-release-weight: 30000
hotfix:
mode: ContinuousDeployment
tag: beta
increment: Patch
prevent-increment-of-merged-branch-version: false
track-merge-target: false
regex: ^hotfix(es)?[/-]
source-branches:
- develop
- master
- support
tracks-release-branches: false
is-release-branch: false
is-mainline: false
pre-release-weight: 30000
support:
mode: ContinuousDeployment
tag: ''
increment: Patch
prevent-increment-of-merged-branch-version: true
track-merge-target: false
regex: ^support[/-]
source-branches:
- master
tracks-release-branches: false
is-release-branch: false
is-mainline: true
pre-release-weight: 55000
ignore:
sha: []
commit-date-format: yyyy-MM-dd
merge-message-formats: {}
Hopefully that helps.

Apparently, what I was attempting to do really isn't the way to pass along the version number. Instead, I am now using a transform to update the value in my JSON configuration and that is being published as the build artifact. Here is my current iteration of my azure-pipelines.yml:
name: $(date:yyyyMMdd)$(rev:.r)-$(Build.SourceBranchName)-$(GitVersion.SemVer)
trigger:
- master
- develop
stages:
- stage: DEV
displayName: 'DEV'
condition: and(always(), contains(variables['Build.SourceBranch'], 'develop'))
pool:
vmImage: 'ubuntu-latest'
variables:
contentVersion: $(GitVersion.AssemblySemVer)
parameters.semVer.value: $(GitVersion.AssemblySemVer)
parameters.resourceGroupName.value: 'rgName-DEV'
jobs:
- job: DevResourceGroup
steps:
- task: GitVersion#5
inputs:
preferBundledVersion: false
updateAssemblyInfo: true
configFilePath: './GitVersion.yml'
- script: echo %Action%%BuildVersion%
displayName: 'Set Build Number to Semantic Version'
env:
Action: '##vso[build.updatebuildnumber]'
BuildVersion: '$(GitVersion.SemVer)'
- task: FileTransform#2
inputs:
folderPath: '$(Build.SourcesDirectory)'
xmlTransformationRules:
jsonTargetFiles: './ResourceGroup/resourceGroup.parameters.json'
- task: AzureResourceManagerTemplateDeployment#3
inputs:
deploymentScope: 'Subscription'
azureResourceManagerConnection: 'ConnectionName'
subscriptionId: 'GUID'
location: 'East US'
templateLocation: 'Linked artifact'
csmFile: '$(Build.SourcesDirectory)/ResourceGroup/resourceGroup.json'
csmParametersFile: '$(Build.SourcesDirectory)/ResourceGroup/resourceGroup.parameters.json'
deploymentMode: 'Incremental'
- task: PublishBuildArtifacts#1
inputs:
PathtoPublish: '$(Build.SourcesDirectory)'
ArtifactName: 'develop'
publishLocation: 'Container'
- stage: PROD
displayName: 'PROD'
condition: and(always(), contains(variables['Build.SourceBranch'],'master'))
pool:
vmImage: 'ubuntu-latest'
variables:
contentVersion: $(GitVersion.AssemblySemVer)
parameters.semVer.value: $(GitVersion.AssemblySemVer)
jobs:
- job: ProdResourceGroup
steps:
- task: GitVersion#5
inputs:
preferBundledVersion: false
updateAssemblyInfo: true
configFilePath: './GitVersion.yml'
- script: echo %Action%%BuildVersion%
displayName: 'Set Build Number to Semantic Version'
env:
Action: '##vso[build.updatebuildnumber]'
BuildVersion: '$(GitVersion.SemVer)'
- task: FileTransform#2
inputs:
folderPath: '$(Build.SourcesDirectory)'
xmlTransformationRules:
jsonTargetFiles: './ResourceGroup/resourceGroup.parameters.json'
- task: AzureResourceManagerTemplateDeployment#3
inputs:
deploymentScope: 'Subscription'
azureResourceManagerConnection: 'ConnectionName'
subscriptionId: 'GUID'
location: 'East US'
templateLocation: 'Linked artifact'
csmFile: '$(Build.SourcesDirectory)/ResourceGroup/resourceGroup.json'
csmParametersFile: '$(Build.SourcesDirectory)/ResourceGroup/resourceGroup.parameters.json'
deploymentMode: 'Incremental'
- task: PublishBuildArtifacts#1
inputs:
PathtoPublish: '$(Build.SourcesDirectory)'
ArtifactName: 'master'
publishLocation: 'Container'
So, I take the version I want, write it to the JSON file and that will be available in my release pipeline.

After tested on my test project. I found $($GITVERSION_MAJORMINORPATCH) cannot get the version value, and $env:Version cannot be refer to variable Version. I made below changes to your build yml file and then it worked just as expected.
- task: PowerShell#2
inputs:
targetType: 'inline'
script: |
$versionInfo = '$(GitVersion.MajorMinorPatch)'
Write-Host("##vso[task.setvariable variable=Version;]$versionInfo")
Write-Host($versionInfo)
- script: echo %Action%%BuildVersion%
displayName: 'Set build version'
env:
Action: '##vso[build.updatebuildnumber]'
BuildVersion: '$(Version)'
In the powershell task I used $(GitVersion.MajorMinorPatch) to reference to the gitversion. And used $(Version) to get the version string for BuildVersion

Related

Azure devops yaml, filter parameter with string

Short question: how do I do the "enable" part in the pipeline below?
Long question: I have 3 jobs that I need to generate dynamically based on the parameters "params" due to business requirements. The job generated only works if the Job1, Job2 or Job3 is selected as true. Can I access parameters using string like dynamic in c#? ie: parameters["Job1"] or parameters["Job2"] or parameters["Job3"] ?
trigger: none
#Package Parameter
parameters:
- name: Job1
displayName: 'Job1'
type: boolean
default: false
- name: Job2
displayName: 'Job2'
type: boolean
default: false
- name: Job3
displayName: 'All Teams'
type: boolean
default: false
- name: 'params'
type: object
default: ["Job1",
"Job2",
"Job3"]
pool:
vmImage: ubuntu-latest
stages:
- stage: Build_dev
dependsOn:
jobs:
- ${{ each testJob in parameters.params }}:
- job:
enable: **If(parameters[testJob] == true) then enable this job**
displayName: Build ${{ testJob }}
steps:
- script: Build ${{ testJob }}
This is one way you can disable the jobs that are not set as true in the parameters. You can also use conditions for your jobs to skip them
azure-pipeline.yml
trigger: none
#Package Parameter
parameters:
- name: Job1
displayName: 'Job1'
type: boolean
default: false
- name: Job2
displayName: 'Job2'
type: boolean
default: false
- name: Job3
displayName: 'All Teams'
type: boolean
default: false
pool:
vmImage: ubuntu-latest
stages:
- stage: Build_dev
dependsOn: []
jobs:
- ${{ each parameter in parameters }}:
- ${{ if eq(parameter.Value, 'true') }}:
- template: job-template.yml
parameters:
jobName: ${{ parameter.Key }}
job-template.yml
parameters:
jobName: ''
jobs:
- job: ${{ parameters.jobName }}
displayName: Build ${{ parameters.jobName }}
steps:
- script: echo "Build ${{ parameters.jobName }}"

AzureDevops Pipeline Templates From Folder

I am trying to use templates in my pipeline that are in the same project folder but on Validate yam and run pipeline gives me an error
/templates/transform-settings.yml (Line: 1, Col: 1): A sequence was not expected
Here is the part of azure-pipelines.yml and template:
imagePullSecret: ' fd bfgbgf '
dockerfilePath: '**/Dockerfile'
vmImageName: 'ubuntu-latest'
testVar: 'test'
tag: '$(Build.BuildId)'
ConnectionStrings.DefaultConnection: ""
stages:
- template: templates/transform-settings.yml
- stage: Build
displayName: Build stage
jobs:
- job: Build
displayName: Build
pool:
vmImage: $(vmImageName)
steps:
- task: Docker#2
inputs:
command: buildAndPush
repository: $(imageRepository)
dockerfile: $(dockerfilePath)
containerRegistry: $(dockerRegistryServiceConnection)
.... and template:
- stage: TransformFiles
displayName: TransformFiles
variables:
- ${{ if eq(variables['Build.SourceBranchName'], 'development') }}:
- group: dev-secrets
- name: testVar
value: 'dev'
- name: ConnectionStrings.DefaultConnection
value: $(psql-conn-str-dev)
- ${{ if eq(variables['Build.SourceBranchName'], 'qa') }}:
- group: qa-secrets
- name: testVar
value: 'qa'
jobs:
- job: Transform_AppSettings
steps:
- bash: echo "===== Transforming appsettings.json for $(variables['Build.SourceBranchName']) environment ====="
displayName: 'File Transform'
- task: FileTransform#1
inputs:
folderPath: '$(System.DefaultWorkingDirectory)'
fileType: 'json'
targetFiles: 'appsettings.json'
- upload: appsettings.json
artifact: appsettings
/templates/transform-settings.yml (Line: 1, Col: 1): A sequence was not expected
Based on your yaml sample, the issue is related to the format of the YAML template.
To solve this issue, you need to add the stages: field at the top of the template YAML file.
For example:
azure-pipelines.yml
stages:
- template: templates/transform-settings.yml
- stage: Build
displayName: Build stage
jobs:
- job: Build
displayName: Build
pool:
vmImage: $(vmImageName)
steps:
- task: Docker#2
inputs:
command: buildAndPush
repository: $(imageRepository)
dockerfile: $(dockerfilePath)
containerRegistry: $(dockerRegistryServiceConnection)
transform-settings.yml
stages:
- stage: TransformFiles
displayName: TransformFiles
variables:
- ${{ if eq(variables['Build.SourceBranchName'], 'development') }}:
- group: dev-secrets
- name: testVar
value: 'dev'
- name: ConnectionStrings.DefaultConnection
value: $(psql-conn-str-dev)
- ${{ if eq(variables['Build.SourceBranchName'], 'qa') }}:
- group: qa-secrets
- name: testVar
value: 'qa'
jobs:
- job: Transform_AppSettings
steps:
- bash: echo "===== Transforming appsettings.json for $(variables['Build.SourceBranchName']) environment ====="
displayName: 'File Transform'
- task: FileTransform#1
inputs:
folderPath: '$(System.DefaultWorkingDirectory)'
fileType: 'json'
targetFiles: 'appsettings.json'
- upload: appsettings.json
artifact: appsettings
For more detailed info, you can refer to this doc: YAML template.

Missing step to analyse my project in SonarCloud

I have to create a Azure pipeline to install and deploy my Angular project,
one of those steps not working, in other words, the project doesnt was not found in SonarCloud :
My pipeline is :
parameters:
- name: name
default: '[EPP] Front Client'
type: string
- name: serviceName
default: 'EPP_Client'
type: string
- name: version
default: ''
type: string
jobs:
- job: Build_push_and_deploy_${{ parameters.serviceName }}
displayName: Build push and deploy ${{ parameters.name }}
steps:
- task: AzureKeyVault#1
inputs:
azureSubscription: '$(azureKeyVaultServiceConnection)'
KeyVaultName: '$(azureKeyVaultName)'
SecretsFilter: '*'
RunAsPreJob: false
- task: Docker#2
displayName: 'Build front image'
inputs:
containerRegistry: '$(containerRegistryServiceConnection)'
repository: 'front'
command: 'build'
sonarQubeRunAnalysis: true
arguments: >-
--build-arg ENVFILE=$(environment)
--cache-from $(azAcr)/front:latest
addPipelineData: false
tags: |
$(tag)
latest
- task: Docker#2
displayName: 'Login on ACR $(containerRegistryServiceConnection)'
inputs:
command: login
containerRegistry: $(containerRegistryServiceConnection)
- task: Docker#2
displayName: 'Push front image'
inputs:
containerRegistry: '$(containerRegistryServiceConnection)'
repository: 'front'
command: 'push'
tags: |
$(tag)
- task: HelmInstaller#0
displayName: 'Install Helm and Kubectl'
inputs:
helmVersion: '$(helmVersion)'
checkLatestHelmVersion: false
installKubectl: true
kubectlVersion: '$(kubectlVersion)'
- task: HelmDeploy#0
displayName: 'Deploy EPP-front service'
inputs:
connectionType: 'Kubernetes Service Connection'
kubernetesServiceConnection: '$(kubernetesServiceConnection)'
namespace: 'epp'
command: 'upgrade'
chartType: 'FilePath'
chartPath: 'helm/chart'
releaseName: 'epp-front-service'
overrideValues: 'image.tag=$(tag)'
valueFile: 'helm/values_$(environment).yaml'
arguments: >-
--timeout=15m0s
$(helmExtraArgs)
- task: SonarQubePrepare#5
displayName: 'Prepare analysis configuration'
inputs:
SonarQube: 'EPP'
organization: orga
scannerMode: 'CLI'
configMode: 'manual'
cliProjectKey: 'orga_${{parameters.serviceName}}'
cliProjectName: 'orga_${{parameters.serviceName}}'
cliSources: 'src/app'
extraProperties: |
sonar.projectKey=orga_${{parameters.serviceName}}
sonar.projectName=orga_${{parameters.serviceName}}
sonar.typescript.tsconfigPath=src/app/tsconfig.json
sonar.sources=src/app
sonar.test=src/app
sonar.test.inclusions=src/app/**/*.spec.ts
sonar.exclusions=**/node_modules/*
sonar.javascript.lcov.reportPaths=src/app/coverage/lcov.info,src/app/coverage-e2e/lcov.info
- task: SonarQubeAnalyze#5
displayName: 'Run Code Analysis'
- task: SonarQubePublish#5
displayName: 'Publish results on build summary'
inputs:
pollingTimeoutSec: '300'
on the other side, 'orga' is configured as organization and i had analyse other backedn project.
is there a steps that is missing ? or test step ?
PS : all steps are working properly when running this pipeline.
Error log :
2022-09-29T15:18:35.9334213Z ERROR: Error during SonarScanner execution
2022-09-29T15:18:35.9334796Z ERROR: Could not find a default branch to fall back on.
2022-09-29T15:18:35.9335298Z ERROR:
2022-09-29T15:18:35.9336129Z ERROR: Re-run SonarScanner using the -X switch to enable full debug logging.
2022-09-29T15:18:36.2621538Z ##[error]The process '/SonarQubeAnalyze_6d01813a-9589-4b15-8491-8164aeb38055/5.8.0/sonar-scanner/bin/sonar-scanner' failed with exit code 2
2022-09-29T15:18:36.2678083Z ##[section]Finishing: Run Code Analysis

Conditional dependson for multiple stage YAML

I have a YAML pipeline which contains some template files.
Within my pipeline, there are 4 stages that run in parallel to apply DSC. I then have a destroy task which i would like to run, only when all 4 tasks have ran successfully. When i try to add a depends on with a list:
dependsOn:
- Stage_A
- Stage_B
- Stage_C
- Stage_D
The error I get is:
The 'dependsOn' parameter is not a valid String.
My template YAML looks like:
...
stages:
...
- template: Apply-DSC.yml
parameters:
azureSub: '[sub]'
AutoAccountResourceGroup: 'rg'
AutoAccountName: 'aa'
environment: 'b1'
stageDependsOn: 'b1_apply'
- template: Destroy-Pipeline.yml
parameters:
azureSub: '[sub]'
terraformStorageAccountResourceGroup: 'rg'
terraformStorageAccountName: '[]'
terraformStorageContainerName: '[]'
terraformStorageRemoteStateKey: '[].tfstate'
environment: 'b1'
terraformEnvironmentFileName: 'B01'
dependsOn: 'Stage_A'
I have 4 stages within my Apply-DSC.yml
Stage_A
Stage_B
Stage_C
Stage_D
Question is, is this possible for my destroy stage to await a successful deployment of Stages A-D when using these stage templates?
Thanks.
Edit: Adding Destroy-Pipeline.yml
# Run & upload Terraform plan
parameters:
- name: azureSub
type: string
- name: terraformStorageAccountResourceGroup
type: string
- name: terraformStorageAccountName
type: string
- name: terraformStorageContainerName
type: string
- name: terraformStorageRemoteStateKey
type: string
- name: environment
type: string
- name: terraformEnvironmentFileName
type: string
- name: dependsOn
type: string
stages:
- stage: Destroy_${{ parameters.environment }}
dependsOn: ${{ parameters.dependsOn }}
jobs:
- deployment: '${{ parameters.environment }}_Destroy'
displayName: '${{ parameters.environment }} Destroy'
environment: '${{ parameters.environment }} destroy'
pool:
vmImage: windows-latest
strategy:
runOnce:
deploy:
steps:
- download: current
artifact: 'drop'
name: 'Download_Terraform_code'
displayName: 'Download Terraform code'
- task: ms-devlabs.custom-terraform-tasks.custom-terraform-installer-task.TerraformInstaller#0
inputs:
terraformVersion: '$(TerraformVersion)'
displayName: 'Install Terraform'
- task: TerraformCLI#0
inputs:
command: 'init'
workingDirectory: '$(Pipeline.Workspace)/Drop'
backendType: 'azurerm'
backendServiceArm: '${{ parameters.azureSub }}'
backendAzureRmResourceGroupName: '${{ parameters.terraformStorageAccountResourceGroup }}'
backendAzureRmStorageAccountName: '${{ parameters.terraformStorageAccountName }}'
backendAzureRmContainerName: '${{ parameters.terraformStorageContainerName }}'
backendAzureRmKey: '${{ parameters.terraformStorageRemoteStateKey }}'
allowTelemetryCollection: false
displayName: 'Terraform Init'
- task: PowerShell#2
inputs:
targetType: 'inline'
script: |
terraform workspace select $(WorkspaceEnvironment)
workingDirectory: '$(Pipeline.Workspace)/Drop'
displayName: 'Select Workspace'
- task: TerraformCLI#0
inputs:
command: 'plan'
environmentServiceName: '${{ parameters.azureSub }}'
commandOptions: '-destroy -var-file="./environments/${{ parameters.terraformEnvironmentFileName }}.tfvars" -input=false'
allowTelemetryCollection: false
workingDirectory: '$(Pipeline.Workspace)/Drop'
displayName: 'Plan Destroy'
- task: TerraformCLI#0
inputs:
command: 'destroy'
workingDirectory: '$(Pipeline.Workspace)/Drop'
environmentServiceName: '${{ parameters.azureSub }}'
commandOptions: '-var-file="./environments/${{ parameters.terraformEnvironmentFileName }}.tfvars" -input=false '
allowTelemetryCollection: false
displayName: 'Run Destroy'
I changed the type from string to object
parameters:
- name: dependsOn
type: object
default: []
Then within my template block i added the object like:
- template: Destroy-Pipeline.yml
parameters:
...
dependsOn: ['Stage_A', 'Stage_B' ...]

YAML pipeline : How to disable a template depending on variable

I have a yaml pipeline calling a step AndroidSigning#3 which needs apksignerKeystoreFile input. I want to disable this step depending on a variable in the pipeline's library.
I get this error when starting the pipeline :
/build/pipelines/build-mobile-android.yml (Line: 42, Col: 14): Unexpected value 'ne(, 'release')'
Any help is appreciated
- group: variables-group
stages:
- stage: build
jobs:
- job: buil_app
steps:
- task: AndroidSigning#3
enabled: ne(${{ variables.env }}, 'release')
inputs:
apkFiles: 'blabla'
apksign: true
Looking at YAML schema reference it looks that this is not possible here
steps:
- script: string # contents of the script to run
displayName: string # friendly name displayed in the UI
name: string # identifier for this step (A-Z, a-z, 0-9, and underscore)
workingDirectory: string # initial working directory for the step
failOnStderr: boolean # if the script writes to stderr, should that be treated as the step failing?
condition: string
continueOnError: boolean # 'true' if future steps should run even if this step fails; defaults to 'false'
enabled: boolean # whether to run this step; defaults to 'true'
enabled must be boolean. You may use condition and then ne( variables['env'], 'release') it should do the job.
steps:
- task: AndroidSigning#3
condition: eq(variables['env'], 'release')
displayName: AndroidSigning - enabled
enabled: true
inputs:
apkFiles: 'blabla'
apksign: true
- task: AndroidSigning#3
condition: ne(variables['env'], 'release')
displayName: AndroidSigning - disable
enabled: false
inputs:
apkFiles: 'blabla'
apksign: true