Set TFS build version number PowerShell - 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()

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.

Access SourceBranchName in Release pipeline

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

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.

Get Build status by Commit SHA1

Our team is using TeamCity for continuous integration and Git-TFS (TFS2015 RC) for versioning.
I want to check if a specific Commit has been built (successfully) by TeamCity and thus can be reintegrated.
It is possible to query TeamCity builds by using their REST API, e.g.:
GET http://teamcity:8000/guestAuth/app/rest/builds/18
with the result containing some xml that shows the git commit SHA:
<revisions count="1">
<revision version="96b1db05b64ecc895da070137e93cde3d2cadfa1">
<vcs-root-instance [...]/>
</revision>
</revisions>
The fact, that this information is in theory available, makes me hope that it is possible to query TeamCity builds by this particular information, like:
GET http://teamcity:8000/guestAuth/app/rest/builds/revision:96b1db05b64ecc895da[...]
but this yields a #400 BAD REQUEST response. I was not able to find out in the TeamCity 9 Documentation, whether this is possible or not. I would rather not iterate all builds to check if they contain this specific commit.
NOTE: This feature has now been implemented by JetBrains and is available in TeamCity 9.1 EAP4 now.
I don't believe this can be done without iteration, which is a little annoying
You can view changes by hash
/httpAuth/app/rest/changes?version:SHA_HASH
and you can find changes by build locator
/httpAuth/app/rest/changes?locator=build:(id:BUILD_ID)
but you can't go the other way, otherwise this could be done simply.
The buildLocator doesn't allow you to query using a revision dimension so I can't see any way around this
The following script may be of use to you if you haven't already written it yourself - save this to a file called get-build-status-by-git-commit.ps1 so it works with the sample at the end
# -----------------------------------------------
# Get Build Status By Git Commit
# -----------------------------------------------
#
# Ver Who When What
# 1.0 DevOpsGuys 01-07-15 Initial Version
# Script Input Parameters
param (
[ValidateNotNullOrEmpty()]
[string] $TeamCityServer = $(throw "-TeamCityServer is mandatory, please provide a value."),
[ValidateNotNullOrEmpty()]
[string] $ApiUsername = $(throw "-ApiUsername is mandatory, please provide a value."),
[ValidateNotNullOrEmpty()]
[string] $ApiPassword = $(throw "-ApiPassword is mandatory, please provide a value."),
[ValidateNotNullOrEmpty()]
[string] $GitSha = $(throw "-GitSha is mandatory, please provide a value.")
)
function Main()
{
$CurrentScriptVersion = "1.0"
$ApiCredentials = New-Object System.Management.Automation.PSCredential($ApiUsername, (ConvertTo-SecureString $ApiPassword -AsPlainText -Force))
Write-Host "================== Get Build Status By Git Commit - Version"$CurrentScriptVersion": START =================="
# Log input variables passed in
Log-Variables
Write-Host
# Set initial query url
$queryBuilds = "/httpAuth/app/rest/builds?fields=nextHref,build(id,status,revisions)"
while($queryBuilds)
{
$buildsToCheck = Api-Get "$TeamCityServer$queryBuilds"
$queryBuilds = $buildsToCheck.builds.nextHref;
foreach($build in $buildsToCheck.builds.build)
{
if ($build.revisions.revision.version -eq $GitSha) {
Write-Host "STATUS: "$build.status
Exit 0
}
}
}
Write-Host "================== Get Build Status By Git Commit - Version"$CurrentScriptVersion": END =================="
}
function Log-Variables
{
Write-Host "TeamCityServer: " $TeamCityServer
Write-Host "GitSha: " $GitSha
Write-Host "Computername:" (gc env:computername)
}
function Api-Get($Url)
{
Write-Host $Url
return Invoke-RestMethod -Credential $ApiCredentials -Uri $Url -Method Get -TimeoutSec 20;
}
Main
You can use this in the following way
.\get-build-status-by-git-commit.ps1 "http://teamcity:8000/" username password 96b1db05b64ecc895da070137e93cde3d2cadfa1
This is using httpAuth, but you could easily tailor the script to be using guest. I've used httpAuth in case it's of use to anyone else.
Hope this helps
I was looking for the same thing and stumbled upon this question. I don't know if you still need this but however I found the API in TeamCity v10. But you have to know your BuildTypeID for this
https://${teamcity.domain}/app/rest/buildTypes/id:${BuildTypeID}/builds/revision:${COMMIT_SHA}
You can find your build type id from TeamCity UI by going to your specific build and then
Edit configuration settings >> General Settings
And then the value in the Build configuration ID field.
Hope this helps.
The related feature request in TeamCity issue tracker: https://youtrack.jetbrains.com/issue/TW-40540. Vote for it.
The current workaround is to request builds with their revisions included into the response and then find the necessary builds on the client side.
The request can look like:
.../app/rest/builds?locator=buildType(id:XXX)&fields=build(id,href,revisions(revision))
Recent versions of teamcity allow the 'version' locator such that the following will return builds where the version SHA matches the query.
http://teamcity:8111/app/rest/changes?locator=version:SHA_HASH
I'm on TeamCity 2019.2, and I was able to directly search the builds endpoint for a specific commit:
TEAMCITY_URL/app/rest/builds/revision:SHA_HASH.
Not sure what version it was implemented in.

From Msi , how to get the list of files packed in each feature?

We have used wix to create Msi. Each Msi will be having 1 or 2 or 3 features such as Appserver feature, Webserver feature and DB server feature.
Now i was asked to get the list of config files presented in each feature.
It is tough to find the list of web.config files associated with each feature through wxs file.
Is it possible find the list of files associated with a feature with particular search pattern?
For ex. Find all the web.config files packed in Appserver feature.
Is there any way easy way ( querying or some other automated script such as powershell) to get the list?
Wix comes with a .NET SDK referred to as the DTF ("deployment tools foundation"). It wraps the windows msi.dll among other things. You can find these .NET Microsoft.Deployment.*.dll assemblies in the SDK subdirectory of the Wix Toolset installation directory. The documentation is in dtf.chm and dtfapi.chm in the doc subdirectory.
As shown in the documentation, you can use this SDK to write code which queries the msi database with SQL. You will be interested in the Feature, FeatureComponents and File tables.
If you haven't explored the internals of an MSI before, you can open it with orca to get a feel for it.
You can do it by making slight modifications to the Get-MsiProperties function described in this PowerShell article.
Please read the original article and create the prescribed comObject.types.ps1xml file.
function global:Get-MsiFeatures {
PARAM (
[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,HelpMessage="MSI Database Filename",ValueFromPipeline=$true)]
[Alias("Filename","Path","Database","Msi")]
$msiDbName
)
# A quick check to see if the file exist
if(!(Test-Path $msiDbName)){
throw "Could not find " + $msiDbName
}
# Create an empty hashtable to store properties in
$msiFeatures = #{}
# Creating WI object and load MSI database
$wiObject = New-Object -com WindowsInstaller.Installer
$wiDatabase = $wiObject.InvokeMethod("OpenDatabase", (Resolve-Path $msiDbName).Path, 0)
# Open the Property-view
$view = $wiDatabase.InvokeMethod("OpenView", "SELECT * FROM Feature")
$view.InvokeMethod("Execute")
# Loop thru the table
$r = $view.InvokeMethod("Fetch")
while($r -ne $null) {
# Add property and value to hash table
$msiFeatures[$r.InvokeParamProperty("StringData",1)] = $r.InvokeParamProperty("StringData",2)
# Fetch the next row
$r = $view.InvokeMethod("Fetch")
}
$view.InvokeMethod("Close")
# Return the hash table
return $msiFeatures
}