Содержание
Azure DevOps
Tasks / Задачи - https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/reference/?view=azure-pipelines
Expressions / Выражения - https://docs.microsoft.com/en-us/azure/devops/pipelines/process/expressions?view=azure-devops
Переменные
Обновить переменную pipeline releases через api
- Добавить переменную в pipline (пример для переменной v1030)
- Добавить разрешений на редактирование pipeline: Pipeline → Releases → Name-Pipeline → More actions → Security → Users: Name-Project Build Service (company) → Edit release pipeline: Allow
- Разрешить скриптам доступ к токену OAuth: Name-Pipeline → Edit → Tasks: Name-Task → Deployment group job|Agent job → Additional options → Allow scripts to access the OAuth token: Enable
- Создать задачу, примрер на powershell inline:
$url = "$($env:SYSTEM_TEAMFOUNDATIONSERVERURI)$env:SYSTEM_TEAMPROJECTID/_apis/Release/definitions/$($env:RELEASE_DEFINITIONID)?api-version=5.0" Write-Host "URL: $url" $pipeline = Invoke-RestMethod -Uri $url -Headers @{ Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" } Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)" # Update an existing variable named v1030 to its new value 1035 $pipeline.variables.v1030.value = "1035" ####****************** update the modified object ************************** $json = @($pipeline) | ConvertTo-Json -Depth 99 $updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"} write-host "==========================================================" Write-host "The value of Varialbe 'v1030' is updated to" $updatedef.variables.v1030.value write-host "=========================================================="
- Переменная доступна как: «$(v1030)» или «$env:v1030»
Создать переменную между task
Job 1, powershell:
Write-Host "##vso[task.setvariable variable=testvar;]testvalue"
Job 2, powershell:
Write-Host "Using testvar: $($env:testvar) = $(testvar)"
https://docs.microsoft.com/en-us/azure/devops/pipelines/scripts/logging-commands?view=azure-devops&tabs=bash
https://medium.com/microsoftazure/how-to-pass-variables-in-azure-pipelines-yaml-tasks-5c81c5d31763
Версия pipeline
Установить build версию в YAML:
version: $[format('{0:yyMM}.{0:dd}.{1}.{2}', pipeline.startTime, variables['system.pullRequest.pullRequestId'], counter(format('{0:yyyyMMdd}-{1}', pipeline.startTime, variables['Build.SourceBranchName']), 1))]
Пример присвоения: 2108.07.2424.1
Обновить build версию:
echo "##vso[build.updatebuildnumber]$version"
Write-Host "##vso[build.updatebuildnumber]$version"
Обновить release версию:
echo "##vso[release.updatereleasename]$version"
Write-Host "##vso[release.updatereleasename]$version"
Логирование
Команды ведения журнала - https://learn.microsoft.com/ru-ru/azure/devops/pipelines/scripts/logging-commands
Tag
Добавить tag на commit из pipeline:
- Добавить persistCredentials: true в checkout:
steps: - checkout: self fetchDepth: 1 clean: true persistCredentials: true
- Добавить задачу для установки tag:
- script: | git tag $(tag) git push --tags workingDirectory: $(Build.SourcesDirectory) displayName: 'git tag $(tag)'
- Добавить пользователя Project Collection Build Service в Contributors:
- %PROJECT% → Settings → Permissions → Contributors → Members → Add
- Отключить опцию Limit job authorization scope to current project for non-release pipelines:
- %PROJECT% → Settings → Pipelines: Settings → General
Tag Pipeline
Добавить тэг migrations на pipeline
Write-Host "##vso[build.addbuildtag]migrations"
https://piotr.gg/dev-ops/add-tag-to-you-build-in-azure-devops.html
submodules
Для доступа pipeline к репозиториям в других проектах, в проекте с этим pipeline:
- Отключить опцию Limit job authorization scope to current project for non-release pipelines и Protect access to repositories in YAML pipelines:
- %PROJECT% → Settings → Pipelines: Settings → General
https://github.com/microsoftdocs/azure-devops-docs/issues/11939
Версия build
Пример добавления префикса к версии сборки в зависимости от ветки:
name: $(version) variables: ${{ if contains(variables['Build.SourceBranch'],'/pull/') }}: version: $[format('{0}.{1}',variables['system.pullRequest.pullRequestId'],counter(variables['system.pullRequest.pullRequestId'], 0))] ${{ if in(variables['Build.SourceBranchName'], 'main','master') }}: version: $[format('{0}.{1:yyMM}.{1:dd}.{2}', variables['majorVersion'], pipeline.startTime, counter(format('{0:yyyyMMdd}-{1}', pipeline.startTime, variables['Build.SourceBranchName']), 1))] ${{ if and(not(contains(variables['Build.SourceBranch'], '/pull/')),notIn(variables['Build.SourceBranchName'], 'main','master')) }}: version: $[format('{0}.{1:yyMM}.{1:dd}.{2}-{3}', variables['majorVersion'], pipeline.startTime, counter(format('{0:yyyyMMdd}-{1}', pipeline.startTime, variables['Build.SourceBranchName']), 1), variables['Build.SourceBranchName'])]
Checkout
Checkout без --tags (в конце обязательно поставить job «git unset»):
https://github.com/microsoft/azure-pipelines-agent/blob/master/docs/design/percentEncoding.md
Извлечение внешнего репозитория
Аутентификация через токен
Кодировать токен в base64 (добавить префикс pat:):
TOKEN64=$(echo -n "pat:${TOKEN}" | base64)
Клонировать репозиторий с помощью токена:
git -c http.extraheader="AUTHORIZATION: basic ${TOKEN64}" clone https://dev.azure.com/ORGNAME/PROJECT/_git/REPOSITORY
Agent
Azure DevOps → Organization Settings → Agent pools → Add pool
Azure DevOps → User settings → Personal Access Tokens → New Token → Agent Pools: Read & Manage
docker build -t azureagent . docker run -e AZP_URL=https://organization.visualstudio.com -e AZP_AGENT_NAME=dockeragent -e AZP_POOL=Docker -e AZP_TOKEN=secret-token --rm -d azureagent
https://docs.microsoft.com/Ru-Ru/Azure/Devops/pipelines/agents/docker?view=azure-devops
Ошибки
TLS1.2
https://github.com/microsoft/azure-devops-tls12 - скрипт для «смягчения» последствий перехода на TLS 1.2
https://stackoverflow.com/questions/70929356/azure-pipelines-local-agent-failing-to-connect-with-ssl-error
https://devblogs.microsoft.com/visualstudio/azure-devops-requires-tls-1-2-on-all-connections-including-visual-studio/
fatal: Cannot prompt because terminal prompts have been disabled.
Решение: Включить передачу токена в checkout pipeline: persistCredentials
https://learn.microsoft.com/en-us/azure/devops/pipelines/yaml-schema/steps-checkout
Checkout
