Need to use Variable groups as Input parameters in Azure pipeline - azure

I am very new to Azure pipeline and I am stuck in an issue from pas one week.
I have a Selenium c# test case which I have to execute on pipeline.
I must use the Variable groups as the input parameters for my test cases.
So, I have created appsettings.json file
appsettings.json
In my YAML code, I am able to read the variable groups, but I am not able to use it's values in the pipeline.How to do it?

To use a variable from a variable group, you need to add a reference to the group in your YAML file:
variables:
- group: my-variable-group
Thereafter variables from the variable group can be used in your YAML file.
If you use both variables and variable groups, you'll have to use name/value syntax for the individual (non-grouped) variables:
variables:
- group: my-variable-group
- name: my-bare-variable
value: 'value of my-bare-variable'
To reference a variable group, you can use macro syntax or a runtime expression. In this example, the group my-variable-group has a variable named myhello.
variables:
- group: my-variable-group
- name: my-passed-variable
value: $[variables.myhello] # uses runtime expression
steps:
- script: echo $(myhello) # uses macro syntax
- script: echo $(my-passed-variable)
You can also reference multiple variable groups in the same pipeline, and link an existing Azure key vault to a variable group and map selective vault secrets to the variable group.
Check Add & use variable groups for more information and examples. Refer to this blog post for a detailed walkthrough.

Related

Azure DevOps PowerShell - Can I build the variable string for a library group variable

PowerShell 5.1
Library variable name in Group: test.DEV
Azure DevOps Parameter value: config
I want to build the variable name test.DEV and then get the value for it that is stored in Library variables of Azure DevOps. For the output, I'm getting the variable name instead of the variable value. Is this even possible?
steps:
- powershell: |
$myVar = "test.${{ parameters.config }}"
'$($myVar)'
Output:
test.DEV
Expected the value for test.DEV instead of variable name
From your description, you need to use nested variable in Azure Pipeline.
Example: $($myVar)
I am afraid that there is no built-in method in Azure pipeline can achieve this.
To meet your requirement, you can use the Variable Set task from extension: Variable Toolbox.
Here is an example:
Variable Group:
Pipeline YAML:
parameters:
- name: config
type: string
pool:
vmImage: ubuntu-latest
variables:
- group: test
steps:
- task: VariableSetTask#3
inputs:
variableName: 'myVar'
value: '$(test.${{ parameters.config }})'
- powershell: |
echo $(myVar)
Result:
Yes, it is possible to name a variable, or set a string variable's value, to the name of a variable itself. I did this on purpose recently as I wanted to create and maintain some dynamically named variables.
Using -f and string placement in that fashion seems to work:
WPS 5.1:
PS C:\pwsh> $testVar = "test.{0}" -f $psversiontable.CLRVersion
PS C:\pwsh> $testVar
test.4.0.30319.42000
I think it auto-converts to a string here because we're using -f.
For naming a variable programmatically (or with reserved characters like dots) you can use the New-Variable cmdlet:
PS C:\pwsh> New-Variable -name "testVar3.stuff" -value $psversiontable.CLRVersion.toString()
PS C:\pwsh> ${testVar3.stuff}
test.4.0.30319.42000
Here I had to convert it to a string manually, otherwise it sets the value to the specified object.
New-Variable is very useful in this context, I think, because you can do all the string mangling you want for both the -name and -value switches without funny escaping. It's a bit verbose, but it's both readable and explicit, which I tend to prefer.

Assign Azure Powershell variable to DevOps Pipeline variable

How can I assigned the $NewIP variable precalculated in this step to a DevOps pipeline variable called $pipeline_ip?
You should use logging command if you want to assign powershell variable to Azure DevOps variable
echo "##vso[task.setvariable variable=pipeline_ip;]$NewIP"
Update after clarification:
If you use syntax like:
$NewIP = $(pipeline_ip)
Then $(pipeline_ip) would be replaced with the value before script will be executed.
And if you use syntax like
$NewIP = $env:PIPELINE_IP
then you will refer to environment variable and since all DevOps variables are mapped (except secret variables - here you need to express this excplicitly) it would also work.
However, these are two ways of doing that.
You can use two methods:
$NewIP = $(pipeline_ip) Macro syntax variables
$NewIP = $env:PIPELINE_IP Set variables in pipeline

Azure Pipeline Matrix Strategy Variable Expansion problem in conjunction with templates

For often used tasks in azp I created an own repository with a yml file, I'll show you a subpart of that:
create-and-upload-docu.yml:
parameters:
- name: Documentation
type: string
default: ''
- name: Language
type: string
default: ''
- name: ArchiveBaseDir
type: string
default: ''
steps:
- script: |
ARCHIVERELPATH=${{parameters.Documentation}}-${{parameters.Language}}.zip
ARCHIVEDIR=$(echo -n ${{parameters.ArchiveBaseDir}} | sed -e 's#/$##')/${{parameters.Documentation}}/${{parameters.Language}}
echo "##vso[task.setvariable variable=archiveRelPath;isOutput=true]$ARCHIVERELPATH"
echo "##vso[task.setvariable variable=archiveDir;isOutput=true]$ARCHIVEDIR"
name: ${{parameters.Documentation}}_${{parameters.Language}}_params
- task: DeleteFiles#1
inputs:
Contents: '$(Build.ArtifactStagingDirectory)/$(${{parameters.Documentation}}_${{parameters.Language}}_params.archiveRelPath)'
The relevant part is: the "script" has the name which is unique in a job - so I can use this kind of expansion for setting variables within the template:
$(${{parameters.Documentation}}_${{parameters.Language}}_params.archiveRelPath)
This works fine as long as I had called the template with fixed values, like
- template: create-and-upload-docu.yml#templates
parameters:
Documentation: 'adocuvalue'
Language: 'en_US'
ArchiveBaseDir: '$(Build.ArtifactStagingDirectory)/build/'
But now I want to use a matrix to have a few documentations with a few languages:
jobs:
- job: Documentation_CI
displayName: "Docu CI"
timeoutInMinutes: 30
strategy:
matrix:
main_en_US:
Documentation: main
Language: en_US
main_de_AT:
Documentation: main
Language: de_AT
steps:
- checkout: self
- template: create-and-upload-docu.yml#templates
parameters:
Documentation: ${{variables.Documentation}}
Language: ${{variables.Language}}
ArchiveBaseDir: '$(Ws)/build/'
But at the time where ${{}} expressions are expanded, it seems that the matrix variables are not already set; this means that the template script part is called __params and the pipeline has the following error
Publishing build artifacts failed with an error: Input required: ArtifactName
Is there a somewhat simple way to achive what I want (being able to set some variables within templates with a unique naming schema):
can I somehow use ${{ expressions but need a different naming to get to the hard-coded matrix style variables
can I workaround my problem any simple way?
Additional Info: we run a Azure 2020 on prem.
Is there a somewhat simple way to achive what I want (being able to set some variables within templates with a unique naming schema):
Sorry for any inconvenience.
I am afraid there is no such way to resolve this at this moment.
Just as you test, the syntax ${{}} is parsed at compile time. We could not get the value when we use it as name or display name in the task, since it will be parsed at compile time. But the matrix variables have not been set during compilation. That the reason why we get the value _params.
There is a feature request about this. And you could add your request for this feature on our UserVoice site (https://developercommunity.visualstudio.com/content/idea/post.html?space=21 ), which is our main forum for product suggestions:

Not getting any values from variables in variable groups in Azure Devops pipeline

I am really struggling with some variables which I have in my variable group named 'android-pipeline'.
Inside this variable group, I have some variables with values.
But when I am running the pipeline it cannot read the values inside my variable group. :(
Example:
Inside the variable group, I have a variable called
$(key.alias)
I am trying to get this value which is behind the variable, see my code below.
I think something is wrong with the syntax (or the way I am using it), but I cannot find the right syntax for using my $(key.alias) variable.
Also, inside the variable group I have made sure that All pipelines have access to this Variable group.
Can someone, please tell me how I can get the value behind the $(key.alias) variable and use this in a task? I tried to follow many guides, but none are clear enough for me or not working
variables:
group: android-pipeline
buildConfiguration: 'Release'
stages:
stage: Publish
dependsOn: Build
displayName: Sign Apps
jobs:
- task: AndroidSigning#3
displayName: Android App signing
inputs:
apkFiles: '**/*.apk'
apksignerKeystoreFile: '$(androidKeyStore)'
apksignerKeystorePassword: '********'
apksignerKeystoreAlias: '$(key.alias)'
apksignerKeyPassword: '*******'
apksignerArguments: --out $(outputDirectory)/app.release.apk
zipalign: true
Since you're mixing groups and inline variables, you may need to change this from a mapping to a sequence, as in:
variables:
- group: android-pipeline
- name: buildConfiguration
value: Release
Normally when you declare variables, you can do them like a mapping, or hashtable, of name/value pairs:
variables
var1: value1 # note there's no dash at the beginning of the line
var2: value2
var3: value3
# etc
When you want to use a group, you have to change your syntax a little, so that the parser doesn't think you want to create a variable named "group" - you turn it into a sequence, or array:
variables
- group: groupname1 # note there's a dash at the beginning of the line
- group: groupname2
# etc
Here's the final wrinkle - once you've gone from the first format to the second (mapping to sequence), you have to declare new variables that are local to your file in the "sequence" style:
variables
- group: groupname1 # note there's a dash at the beginning of the line
- name: varname1
value: value1
- name: varname2
value: value2
# etc
You reference the variable further down in your pipeline the same way, with $(varname1) syntax.
If you're having problems with this, I recommend a couple of things (actually, 3):
Use script or pwsh tasks to echo or Write-Host everything you want to see but aren't, as in "pwsh: Write-Host "My var should be $(varname1)"
Turn on system diagnostics when you run the pipeline and see if the output has any useful details
Edit the pipeline through the portal - Pipelines - select your pipeline -> Edit. Then, from the ellipsis menu in the top right of the page, select "Download full YAML" - this will give download what the compiler would create. Now, it won't give you variable values, but what it can do is give you clues as to possible format or declaration errors.

Howto: Dynamic variable name resolution in Azure DevOps YAML

The consistency of Variable support & the syntax vary wildly in Azure DevOps YAML.
Case in point:
trigger:
- master
# Variable Group has $(testCategory1) with value
# 'TestCategory=bvttestonly | TestCategory=logintest'
variables:
- group: DYNAMIC_VG
jobs:
- job:
pool: 'MyPool' #Has about 10+ self hosted agents
strategy:
parallel: $[ variables['noOfVMsDynamic']]
variables:
indyx: '$(testCategories$(System.JobPositionInPhase))'
indyx2: $[ variables['indyx'] ]
testCategories: $[ variables[ 'indyx2' ] ]
steps:
- script: |
echo "indyx2 - $(indyx2)"
echo "testCategories $(testCategories)"
displayName: 'Display Test Categories'
The step prints:
"indyx2 - $(testCategories1)"
"testCategories $(testCategories1)"
I need to print the value of $(testCategories1) defined in the Variable Group:
'TestCategory=bvttestonly | TestCategory=logintest'
This may work to you:
variables
indyx: $[ variables[format('{0}{1}', 'testCategories', variables['System.JobPositionInPhase'])] ]
It worked for me, in a slightly different situation which also required some dynamic variable names.
Howto: Dynamically resolve a nested variable in Azure DevOps YAML
That because the value of nested variables (like $(testCategories$(System.JobPositionInPhase))) are not yet supported in the build pipelines at this moment.
That the reason why you always get the value $(testCategories1) rather than the real value of variable testCategories1.
I encountered this issue many times in my past posts and we do not have a perfect solution before Azure Devops supports this feature.
For the convenience of testing, I simplified your yaml like following:
jobs:
- job: ExecCRJob
timeoutInMinutes: 800
pool:
name: MyPrivateAgent
displayName: 'Execute CR'
variables:
testCategories1: 123456
testCategoriesSubscripted: $(testCategories$(System.JobPositionInPhase))
strategy:
parallel: $[variables['noOfVMs']]
steps:
- template: execute-cr.yml
parameters:
testCategories: $(testCategoriesSubscripted)
The execute-cr.yml:
steps:
- script: echo ${{ parameters.testCategories }}
We always get the $(testCategories1)NOT the value of it.
If I change the $(testCategories$(System.JobPositionInPhase)) to $(testCategories1), everything work fine.
Since nested variables are not yet supported, As workaround, we need to expand the nested variables for each value of testCategories, like:
- job: B
condition: and(succeeded(), eq(dependencies.A.outputs['printvar.skipsubsequent'], 'Value1'))
dependsOn: A
steps:
- script: echo hello from B
Check the Expressions Dependencies for some more details.
Hope this helps.
If I'm understanding your issue correctly, the problem is that the pipeline evaluates all variables at the runtime of the job. The solution in this scenario is to split your tasks into separate jobs with dependencies.
Have a look at my answer in this post and let me know if it's what you're after : YAML pipeline - Set variable and use in expression for template
I manage to get dynamic name resolution by using get-item to read the corresponding environment variable, allowing construction of the name of the variable and then getting the value.
In our case we save the name of an autogenerated branch into a variable group and each repository will have its own variable.
$branchVarName = "$(Build.Repository.Name).BranchName".replace(".","_")
$branchName = (get-item -Path Env:$branchVarName).value
write-host "/$(System.TeamProject)/_apis/build/builds?&repositoryId=$(Build.Repository.ID)&repositoryType=TFSGit&branchName=refs/heads/$branchName&api-version=6.0"
Notice in the second line that I reference the variable content using .value because get-item returns a name/value key pair.
This extraction has to be done in script but could be exposed as an output variable if needed in another context.

Resources