VSO(TFS) - get current date time as variable - deployment

How can I get a current date-time and pass it as a variable to some Deployment task?

You can define a variable with any value, and then modify the variable as current date. Detail steps as below:
Define a variable in release
Assume the variable name is time, and we set the value as none. If you need to use the variable for a environment, you can define it in environment variables. Else you should define it in variables Tab.
Add a power shell task at the begin of deploy tasks:
Type: Inline Script.
Inline script:
$date=$(Get-Date -Format g);
Write-Host "##vso[task.setvariable variable=time]$date"
Note:
I use the date format as MM/DD/YYYY HH:MM AM/PM here. You can use other date formats.
For the subsequent deploy task, if you want to use current date time, you can direct use $(time).
Update
Documentation for Defining Variables: Set Variables Using Expressions has a nugget of gold for the answer to this question in the example for creating a counter value that is reset daily.
a: $[counter(format('{0:yyyyMMdd}', pipeline.startTime), 100)]
The pipeline.startTime variable used here is subtle and not mentioned anywhere in the Pipeline Predefined Variables documentation, even when being careful to land on the correct documentation based on the pipeline method being used. As is suggested HERE and in some of the answers on this thread, certain variables may have different values or not exist at all depending on where you are while trying to access them.

There is now a variable specific to a release stage named "Release.Deployment.StartTime" or if you use it in powershell the environment variable is "Release_Deployment_StartTime".
It's in UTC and the format is "yyyy-MM-dd HH:mm:ssZ"
ex: "2018-11-09 21:23:27Z"
NOTE: This variable is set at the time the deployment stage is started, so if you have pre-deployment approvals the time will be set before any approvals are completed. From my testing if you have multiple stages that execute at the same time it will be the same between them, even if one stage waits for the other due to limited agent availability.
I'm using Azure DevOps online, unsure if local TFS installations will have this.

For those who use Linux on tfs:
Define variable
Make sure it has "Settable at queue time set"
Create a script in root of your repository
set-build.date.sh:
#!/usr/bin/env bash
DATE=$(date '+%d/%m/%Y %H:%M:%S')
echo "##vso[task.setvariable variable=BUILD_DATE;]$DATE"
Other options are listed here.
Add shell script right after get sources
Type bash to find this task.
Done, you can use BUILD_DATE variable in later tasks :)

An easier way is
$(Date:MMddyy)
Some options are only available in the Build Definition options section. The date formatting is one of them. However, if you were to go into the options section, set the build number format as $(Date:yyyyMMdd-HHmmss), you could then use the $(Build.BuildNumber) variable in your tasks.
More info here - https://learn.microsoft.com/en-us/vsts/build-release/concepts/definitions/build/variables?tabs=batch

Based on answer of Marina Liu (here) for quick copy and paste.
Define variable on top:
variables:
buildTimeStamp: # will be set by script
# ...
Add this as first task (and change format as needed):
- task: PowerShell#2
displayName: set variable buildTimeStamp
inputs:
targetType: 'inline'
script: |
$date=$(Get-Date -Format yyyy-MM-dd_HH.mm);
Write-Host "##vso[task.setvariable variable=buildTimeStamp]$date"
Now you can use variable $(buildTimeStamp) in your code below.

Related

Provide a pipeline queue time variable with default value

In Azure Pipelines you can set pipeline variables at queue time. You can use such a variable the same way as variables defined by the pipeline itself.
Example:
# pipeline.yml
steps:
- checkout: none
- template: steps/some.yml
parameters:
name: $(queueTimeVar)
# steps/some.yml
parameters:
name: 'World'
steps:
- bash: |
echo "Hello ${{ parameters.name }}!"
But if the variable isn't set explicitly, the pipeline evaluates this expresstion to the string itself. The step template would be called with name: '$(queueTimeVar)' and print Hello $(queueTimeVar)!.
How could I set a default value if the variable wasn't set?
I tried adding the default value as variable but it didn't work as expected.
variables:
queueTimeVar: MyDefault
Afterwards the queue time variable had no effect. The variable was always the YAML value.
As workaround I had to add the default handling to every task which uses the value.
# bash task
value="MyDefault"
if [ -n "$QUEUETIMEVAR" ]; then
value="$QUEUETIMEVAR"
fi
How could I set a default value if the variable wasn't set?
If what you mean is does not set this variable queueTimeVar in anywhere, including in Variables tab in trigger page, or Variables tab on YAML configuration page. Unfortunately to say, No, without the variable set explicitly, the server could not know where should get the value.
Until now, if the pipeline configure type you are using is YAML, The server can only recognize the variables which defined in three places: (1) Variable block in YAML script, (2) Variables panel in the configuration page, (3) Variables tab in the Triggers setting.
Any variables which does not defined in one of these three locations are not recognized by the server, even just create one new variable in the below location:
In one word, if you just create a new variable in queue time and have not define it in that three location firstly, the server still could not recognize the variable and its value.
So, you must set variables in one of locations I mentioned previously. Or the pipeline would not get it.

Azure DevOps Release Pipelines - Using env parms with a period . in

I am finding using AZDO Release pipeline variables maddening in Powershell steps.
I am running an Azure PowerShell step to return a primary key value. It is 2 lines…
$primarykey = (Get-AzRelayKey -ResourceGroupName ${env:az-resourcegroupname} -Namespace ${env:az-relaynamespace} -HybridConnection ${env:serviceBus.primaryRelay.ConnectionName} -Name ${env:serviceBus.primaryRelay.KeyName} | Select-Object -ExpandProperty PrimaryKey)
Write-Host "##vso[task.setvariable variable=serviceBus.primaryRelay.Key]$primarykey"
In my pipeline I have a mix of variable names, some I have complete control over (the az- prefixed ones) and others I don’t (the ones starting serviceBus.)
The reason I have no control over the latter is that they are used for a later File Transform step that navigates an appsettings.json file to find/replace values, and its unable to be changed (for example serviceBus.primaryRelay.ConnectionName is a value that is changed in the JSON and the file transform step specifies to navigate the JSON structure, it has to be separated with a period . )
When this script runs it always complains about the -HybridConnection value being empty. This is because the variable has a period in it.
I’ve tried everything I can think of to retrieve that value in the code.
Are they suggesting here that a variable with a period isn’t workable in Powershell in AZDO release pipelines? I’m completely lost.
I have found the answer by looking under the Release Pipelines "Initialize Job" log. It appears to substitute the period . with a dash -
The log revealed this...
[SERVICEBUS_PRIMARYRELAY_CONNECTIONNAME] --> [dev-sbrelay]

Updating a variable in a linked variable group with $(Build.BuildId) from a Linux pipeline

I'd like to update a variable in a linked variable group with $(Build.BuildId) from a Linux pipeline. I see a few examples using the #echo ##vso[task.setvariable command, but can't get it to work because I don't think I'm referencing the source or destination right.
The linked variable group is NightlyBuildID and the variable is LinuxBuildID.
Here's one of my many attempts:
#echo ##vso[task.setvariable variable=LinuxBuildID]$(Build.BuildId)
The $(variable) syntax is only valid within the build editor interface. Within a script, you have to reference it as an environment variable. Periods are replaced with underscores.
Thus, in Linux, $(Build.BuildId) would be accessed as $BUILD_BUILDID.
Apparently, this can't be done, according to the link below. I'll have to come up with a work around, bummer.
https://visualstudio.uservoice.com/forums/330519-visual-studio-team-services/suggestions/32083207-allow-variables-in-variable-groups-to-be-settable

How to pass powershell script variable values to downstream task in Release pipeline

Created a CD with few steps starting from "Azure PowerShell Task".
In Azure PowerShell tasks, executing a PowerShell script file and set a value in a variable.
At the end of the script I have set the variable with a value –
echo "##vso[task.setvariable variable=myvariable;isSecret=false;isOutput=true;]myvalue"
myvariable is the variable
myvalue is the value.
Based on the value of “myvariable”; downstream task will be executed or skipped. Mentioned "Custom Condition" in downstream task (Task - Azure Create or Update Resource) –
and(succeeded(), eq(variables[‘myvariable’], ‘myvalue’))
But, it’s always skipping the step; despite the correct value is passing. Here is my release tasks snippet -
How do I overcome?
try
Write-Host "##vso[task.setvariable variable=myvariable;isSecret=false;isOutput=true;]myvalue"
And then
and(succeeded(), eq(variables['myvariable'], 'myvalue'))
In the second part, the code you pasted in has the incorrect quote types, you had curly quotes ‘ ’ rather than the normal straight quotes ' '
You often end up with the wrong quotes if copying / pasting from Word or Outlook. I'm sure there's a proper a typography term for them.
Thanks everyone for your valuable input. Resolution -
PowerShell Script -
$myvalue="hello"
Write-Host "##vso[task.setvariable variable=myvariable]$myvalue"
Assign value ("hello") in a variable ($myvalue), then set it in "Write-Host". Direct value did not work for me.
Now we can use/verify "myvariable" value in downstream tasks in Custom Condition as mentioned by #Alex KeySmith.
and(succeeded(), eq(variables['myvariable'], 'hello'))
task -
Works in Build and Release pipeline.

Enumerate secret variables in Azure Pipelines

I have a build step in Azure Pipelines that takes the variables from Azure Pipelines and uploads them somewhere equally secret. Currently I have about 50 builds, and each build has anywhere between 5-20 variables.
Some are secret and some are not. So for non secret ones I enumerate all the set ones and off i go; but for secret ones I need to add them to the build step manually; further, because I am writing them with the same keys i need to:
Declare variable in the group e.g. MyPrefix.MyVar
Edit the build step to say /specialtool --vars=MyPrefix.MyVar=$(MyPrefix.MyVar) which is rather mundane.
I found that I can get a list of variables using the Azure DevOps api, so i thought i could just modify the next build step as the build is running.
However, if I update the same build definition that is currently running (to dynamically write the command), it is not sent to the agent (rather, it feels like all arguments for tasks are captured when the whole build is triggered). Any thoughts on how i can dynamically enumerate secret vars to feed to my tool?
You can use VSTS Logging Commands to update variable value during the build. This will make the updated variable to be available in next build task.
Write-Host "##vso[task.setvariable variable=testvar;]testvalue"
When you create a Typescript custom task (NodeJS based), you can access all the build variables that are available to the build at that point in time through the getVariable api.
This function returns an array of VariableInfo:
/** Snapshot of a variable at the time when getVariables was called. */
export interface VariableInfo {
name: string;
value: string;
secret: boolean;
}
When you create a PowerShell3 custom task, you can access all the build variables that are available to the build at that point in time through the Get-VstsTaskVariable function.
Which returns a similar object structure as the Node version:
New-Object -TypeName psobject -Property #{
Name = $info.Name
Value = Get-TaskVariable -Name $info.Name
Secret = $info.Secret
}
If you need to support TFS 2015 and the 1.x build agents as well, you can use (now deprecated) PowerShell handler and enumerate the secrets using a custom powershell function I describe here.
Each task SDK (Typescript and Powershell), supports a function to set variables as well. Here is an example of setting the variable value in Typescript:
tl.setVariable(variable, value, isSecret);
And on PowerShell3:
Set-VstsTaskVariable -name $VariableName -value $Value -Secret $IsSecret
And on PowerShell (deprecated):
Write-Host "##vso[task.setvariable variable=$($VariableName);issecret=$($IsSecret)]$Value"
My suspicion is that you'd want to create a single task that reads the variables and invokes the command you mentioned in your original post to then post these variables to the other secret store. It's not recommended to read all the secrets and either store them in non-secret variables or to somehow pass them along to the next task.
So I have been looking at a solution for this too. It appears the only way to do this at the moment is to write a custom task. Within a custom task you can get hold of secret values dynamically.
An example is the 'vsts-replacetokens-task' (https://github.com/qetza/vsts-replacetokens-task/blob/master/task/index.ts)
Internally it uses the vsts task library (vsts-task-lib/task)
(https://github.com/Microsoft/azure-pipelines-task-lib/blob/master/node/task.ts)
This vsts task library exposes methods like GetVariables() and GetVariable() etc. which can provide what you need. Unfortunately bit long winded, but the only way that I can see.