Access SourceBranchName in Release pipeline - azure-devops

I'm trying to release my buildartifacts to a specific folder based on the name of the sourcebranch which upon creating a pull request triggered the build and therefor the release.
I've managed to so far to get:
write-host $env:RELEASE_TRIGGERINGARTIFACT_ALIAS
$triggerAlias = $env:RELEASE_TRIGGERINGARTIFACT_ALIAS
This alias (from my point of view) is the primary artifcat alias which I need to access
Release.Artifacts.{Primary artifact alias}.SourceBranchName
based on this documentation. So how do I combine the alias to get the sourcebranchname
$env:RELEASE_ARTIFACTS_{$triggerAlias}_SOURCEBRANCHNAME
This doesn't seem to be working and neither does
$env:RELEASE_ARTIFACTS_$($triggerAlias)_SOURCEBRANCHNAME
Any advice is much appreciated.

You can read the variable in this way:
$triggerAlias = $env:RELEASE_TRIGGERINGARTIFACT_ALIAS
$branchNameVariable = "RELEASE_ARTIFACTS_$($triggerAlias)_SOURCEBRANCHNAME"
#Get the value of the environment variable Release.Artifacts.{alias}.SourceBranchName
$branchName = (Get-item env:$branchNameVariable).Value

Related

Is it possible to change the name of a build based on the branch name in Azure Pipelines?

Most of my builds are from either feature branches or develop, and so I tend to use a known build variable to track the build number such as:
variables:
- group: BuildVars
name: $(BuildPrefix)$(Rev:r)
This works and provides me with a nicely formatted build version that I can then follow through into releases, etc:
However, when we're planning a release, we name our branches after the release, for example: release/1.1, and I'd like to have the build name reference that instead of the hardcoded (previous) version.
I know that I can reference the branch name via the Build.SourceBranch variable, but I don't see an obvious way to read and modify that outside of a build step, by which time I believe it's too late? I don't really want to have to manually change the BuildPrefix variable until the release has been deployed out to production.
Building on from this would then be the ability to append appropriate pre-release tags, etc. based on the branch name...
you can always update the build name during the execution of a build using this:
- pwsh: |
Write-Host "##vso[build.updatebuildnumber]value_goes_here"
so you could calculate the value in the same (or previous step) and update the build name with that value
Is it possible to change the name of a build based on the branch name in Azure Pipelines?
The answer is yes.
The solution we currently use is add a Run Inline Powershell task to update build number based on the Build_SourceBranchName:
$branch = $Env:Build_SourceBranchName
Write-Host "Current branch is $branch"
if ($branch -eq "Dev")
{
Write-Host "##vso[build.updatebuildnumber]$DevBuildNumber"
}
elseif ($branch -eq "Beta")
{
Write-Host "##vso[build.updatebuildnumber]$BetaBuildNumber"
}
elseif ($branch -eq "Test")
{
Write-Host "##vso[build.updatebuildnumber]$TestBuildNumber"
}
Check the Logging Command during the build for some more details.
Hope this helps.

How can I delete an Azure DevOps build definition that it claims is retained by a release?

I'm trying to delete an Azure DevOps build definition but it won't let me since it says:
"One or more builds associated with the requested pipeline(s) are retained by a release. The pipeline(s) and builds will not be deleted."
However there's no obvious way to see what release is causing a build to be retained. I tried searching online, of course, but all the examples/screenshots of how to do this in the web UI are showing UI from several iterations ago of the Azure DevOps website so none of the controls look the same anymore. I don't see a lock icon anywhere, for example.
How can I find the releases that are holding onto these build definitions so I can delete them and then delete the build definition?
Thanks!
When you open the build pipeline to see its detailed build records, you can see the relevant release name and its link:
On old pipeline version, there had a lock icon which can obvious let us know it is retained. In fact, the lock icon not only means it is retained by release, manual build retain also show this icon. But, seems we missed this obvious icon while we expand the new sprint.
As a workaround to get list of builds which retained by release, here has a short script can help you achieve by using Rest api:
$token = "{PAT token}"
$url ="https://dev.azure.com/{org name}/{project name}/_apis/build/builds?api-version=5.1"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Get
$results = $response.value | Where {$_.retainedByRelease -eq "true"} #|
Write-Host "results = $($results.id | ConvertTo-Json -Depth 100)"
First, use list builds api to get all builds that in current project. Then for the builds which retained by release, since there has a parameter can indicate it: retainedByRelease here I use $_.retainedByRelease -eq "true" to get the builds list which actual retained by release:
The above script is very universal, can be used in Powershell-ise and Powershell Command Line and the Powershell task of VSTS without change anything.
Update in 11/19:
Based on #Auth's comment, if want to get its associated release, the most easiest way is find the build, and then check its associate release pipeline as the screenshot shown I shared above.
If this does not satisfied what you want, and the previous API we used does not include any releases info in that, so here, you need use this API: Releases - Get Release:
GET https://vsrm.dev.azure.com/{org name}/{project name}/_apis/release/releases?sourceId={project id}:{build definition id}&api-version=5.1
In this API, you need specified the project id:build definition id to filter releases.
With the icon missing, will let the corresponding team know and try to add it in the future sprint.
I have had this issue when some one delete a repository that was associated with a "POC" pipeline. I was not able to delete the pipeline.
When I tried to delete the pipeline, I got following message:
One or more builds associated with the requested pipeline(s) are retained by a release. The pipeline(s) and builds will not be deleted.
I did following steps to delete the pipeline:
My Goal was to delete PublishBuildArtifacts-Infrastructure pipeline as shown in image. So I clicked on the pipeline.
I see list of Builds (Runs) that is associated with my pipeline. I click on the 3 dots and click on View Retention Lease.
Then I click Remove all.
Now you can delete your build.
Repeat steps 2-4 for each run. When you have delete all builds, now you can delete the pipeline by clicking on the 3 dot menu, as shown in the image below.
Enjoy!

Terraform - Pass in Variable to "Source" Parameter

I'm using Terraform in a modular fashion in order to build out my infrastructure. I do this by having a configuration file that calls in the different modules. I want to pass an infrastructure variable which picks up what tagged version of the Github repository the application should be building out. Most importantly I'm trying to figure out how to make a concatenation of a string happen in the "source" variable of the configuration file.
module "athenaelb" {
source = "${concat("git::https://github.com/ORG/REPONAME.git?ref=",var.infra_version)}"
aws_access_key = "${var.aws_access_key}"
aws_secret_key = "${var.aws_secret_key}"
aws_region = "${var.aws_region}"
availability_zones = "${var.availability_zones}"
subnet_id = "${var.subnet_id}"
security_group = "${var.athenaelb_security_group}"
branch_name = "${var.branch_name}"
env = "${var.env}"
sns_topic = "${var.sns_topic}"
s3_bucket = "${var.elb_s3_bucket}"
athena_elb_sns_topic = "${var.athena_elb_sns_topic}"
infra_version = "${var.infra_version}"
}
I want it to compile and for the source to look like this (for example): git::https://github.com/ORG/REPONAME.git?ref=v1
Anyone have any thoughts on how to make this work?
Thanks,
Keren
This is not possible currently in Terraform itself.
The only way to achieve something like this is to use a separate script to interact with the git repository that Terraform clones into a subdirectory of the .terraform/modules directory and switch it to a different tag depending on which version you need. This is non-ideal since Terraform organizes these into directories based on a hash of the module path, but if you can identify the module in question it is safe to run git checkout within these repositories as long as you do not run terraform get again afterwards.
For more details and discussion on this issue, see issue #1439 in Terraform's issue tracker, where this feature was requested.
You could use envsubst or python jinja and use these wrapper scripts in your pipeline deploy script to actually build the scripts from .envsubst and .jinja files before your terraform plan/apply
https://github.com/uvoo/process-templates/tree/main/scripts
I wish terraform would support this but my guess is they never will so just add some simple functions/files into deploy scripts which is usually the best way to deploy.

TFS2015 Variables Issue (Build.SourceBranch and Build.SourceBranchName)

From: https://connect.microsoft.com/VisualStudio/Feedback/Details/2264644
According to: https://msdn.microsoft.com/en-us/library/vs/alm/build/scripts/variables
Build.SourceBranch should map to $/teamproject/branch and Build.SourceBranchName should map to "branch" where the full path is $/teamproject/branch
I have a branch structure like $/MyProject/Development/MyBranch and when I try to use these variables in PowerShell (i.e. using BUILD_SOURCEBRANCH and BUILD_SOURCEBRANCHNAME), I am getting:
BUILD_SOURCEBRANCH: $/MyProject
BUILD_SOURCEBRANCHNAME: MyProject
From my understanding of the article, the variables should return $/MyProject/Development/MyBranch and MyBranch respectively.
Anyone else able to repro this behaviour with a TFVC repository? If you set up a vNext build definition with just a PowerShell task and add the following snippet, you'll be able to see the available variables in the output:
[CmdletBinding()]
param()
$environmentVars = get-childitem -path env:*
foreach($var in $environmentVars)
{
$keyname = $var.Key
$keyvalue = $var.Value
Write-Output "${keyname}: $keyvalue"
}
I have to modify the answer as I have new find. After double checking the MSDN article, I found for TFVC BUILD_SOURCEBRANCH will be the root server path for the workspace. So I tried mapping the branch path to Server Path, please refer to the screenshot below. After specifying the Server Path to the branch path, you will get correct value of BUILD_SOURCEBRANCH.

Set TFS build version number PowerShell

I know that similar question already exist, but I cannot find appropriate answer.
My question is: Is it possible to set new build version number int TFS with PowerShell?
I want to create build version number and set through PowerShell. I want exactly like that, no other solutions.
Thanks
How about this?
# Change the following to your TFS collection and build URIs...
# These environment variables will exist during TFS builds
[String] $CollectionUrl = "$env:TF_BUILD_COLLECTIONURI"
[String] $BuildUrl = "$env:TF_BUILD_BUILDURI"
# Get the Team Project Collection:
$teamProjectCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($CollectionUrl)
# Connect to the TFS build service:
$buildServer = $teamProjectCollection.GetService([Microsoft.TeamFoundation.Build.Client.IBuildServer])
# Get the build detail:
$buildDetail = $buildServer.GetBuild($BuildUrl)
# Updating the TFS build number with an example SemVer:
$buildDetail.BuildNumber = "1.2.3-alpha1"
# Make sure to save the changes:
$buildDetail.Save()