yaml conditional variable assignment

Get notified in your email when a new post is published to this blog

Azure DevOps Pipelines: If Expressions and Conditions

yaml conditional variable assignment

Developer Support

February 16th, 2023 1 2

John Folberth continues his series on Azure DevOps Pipelines by taking a deep dive into If Expressions and Conditions.

At this stage in the series we’ve talked about tasks, jobs, stages, how to template them, and how to leverage environments in variables. This post will attempt to cover some basics around using if and conditions in your YAML Pipelines.  

If Expressions

If expressions  are simple and easy enough in YAML pipelines, they are a powerful tool. In my experience I have leveraged if expressions to:  

  • Conditionally load templates  
  • Dynamically load variables  
  • Enable same pipeline for CI/CD  

The key to unlocking their power is the understanding that an if expression will evaluate at pipeline compilation. This means the pipeline has to leverage known values to apply the logic within. We should not use an if expression when relying on the output of another task/job, the status of another job, or a variable that is updated during pipeline execution.  

The other side of this, since the statement is evaluated at pipeline compilation time, is that we will not load any unnecessary templates into our pipelines. As opposed to conditions, which will we cover next, templates will not appear in the expanded pipeline YAML file. This leads to a cleaner and more secure experience since only what will be executed will appear in the pipeline logs.

Continues reading the full post here and check out the series on the Microsoft Health and Life Sciences Blog .  

yaml conditional variable assignment

Developer Support Cloud Solution Architects, Microsoft Customer Success

yaml conditional variable assignment

Discussion is closed. Login to edit/delete existing comments.

Developer Team,

I want to customize News webpart using SharePoint Framework. I need to get hub associated sites News into webpart and display, i am using v2.1 getNewsFeed api. didn’t find any article related to it. Could some one help me how to expose?

try { var siteURL = this.props.context.pageContext.web.absoluteUrl;

this.props.context.spHttpClient .get( siteURL + // tokenresource + // `_api/v2.1/getNewsFeed?section=SharePointNewsFeedTargeted&$expand=analytics($expand=allTime),thumbnails&$skiptoken=${token}&$top=13`, `/_api/v2.1/getNewsFeed?section=SharePointNewsFeedTargeted&$expand=analytics($expand=allTime),thumbnails&$top=13`, SPHttpClient.configurations.v1, { headers: { ‘authorization’: `Bearer ${token}`, ‘sphome-apicontext’: `{“PortalUrl”:”${siteURL}”}` // ‘sphome-apicontext’: `{“PortalUrl”:”${tokenresource}”}` }} ) .then((responseObj: SPHttpClientResponse) => { responseObj.json().then((responseJSONObj) => { console.log(JSON.stringify(responseJSONObj)); }); }); } catch (ex) { console.warn(ex); }

light-theme-icon

Thomas Thornton Azure Blog

Azure, Azure DevOps, GitHub, Terraform

If, elseif or else in Azure DevOps Pipelines

Writing Azure DevOps Pipelines YAML, have you thought about including some conditional expressions? In this blog post, I am going to show how you can use If, elseif or else expressions to assist in your pipeline creation

Probably the most common expression you may be using is determining if a stage or job can run. There is lots of expressions available in Azure DevOps to assist you.

Azure DevOps Pipeline If, elseif or else expression examples

In this blog post, I will show example usage of these expressions in:

  • Determining which variable to use
  • Determining which task to run
  • Determining which stage to run

if, elseif or else expressions to determine which variable to use

Lets have a look at using these conditional expressions as a way to determine which variable to use depending on the parameter selected.

I have 1 parameter environment with three different options: develop , preproduction and production

Next, is the variable colour that has potential three different outputs, depending on the environment selected. Notice the use of if , elseif and else ?

The stage used to test, is a simple echo return of both parameter & variable values, with full pipeline example:

Selecting the production environment parameter I get the below output:

yaml conditional variable assignment

if, elseif or else expressions to determine which task to run

Moving on, we can use the same expression to determine which task to run within our stage while using the same parameters as previous.

Looking at the pipeline, notice the stage and tasks? The task is determined on the parameters value:

Output of pipeline when parameter environment preproduction has been selected:

yaml conditional variable assignment

if, elseif or else expressions to determine which stage to run

To finish, lets look at the same setup as previous examples – but now, stages!

3 stages, the stage to run is dependent on which parameter is selected:

Selecting parameter environment production , will run stage: stage3

yaml conditional variable assignment

Awesome, i’ve shown 3 examples of how If, elseif or else expressions can and will assist you in your pipeline creation. There is so many ways & use cases for these sort of expressions.

Try various ways, to see how it can recreate your pipeline thoughts – they are great! As always, any queries etc – do give me a shout, always love to hear feedback and seeing different Azure DevOps pipelines being created!

GitHub Repo here – containing all examples used

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to email a link to a friend (Opens in new window)
  • Pingback: Top Stories from the Microsoft DevOps Community - 2022.06.05 - Azure DevOps Blog
  • Pingback: Top Stories from the Microsoft DevOps Community – 2022.06.05 - IT Skills You Need

Great! Thanks for the explanation

  • Pingback: Top Stories from the Microsoft DevOps Community – 2022.06.05 - devopsuk
  • Pingback: If, elseif or else in GitHub Actions – Thomas Thornton – Microsoft Azure MVP – HashiCorp Ambassador

great work man

Thank you for the feedback!

This helped me a lot. Thanks for this!

Thank you for the feedback, glad it assisted you! Please do let me know if there is any additional blog content you would like me to add 🙂

Leave a Reply Cancel reply

Discover more from thomas thornton azure blog.

Subscribe now to keep reading and get access to the full archive.

Type your email…

Continue reading

   SOLUTIONS™

  • Feb 10, 2021

Azure DevOps: If Statements in Your YAML Pipelines

Updated: Jul 11, 2021

If Statements are a fantastic feature in YAML pipelines that allows you to dynamically customize the behavior of your pipelines based on the parameters you pass. They use syntax found within the Microsoft Conditions Documentation . Let's dive in and talk about how you can add them to your pipelines.

Constraints : Where You Can Use If Statements

You cannot use if statements everywhere within your YAML. You'll want to use them only prior to Stages, Jobs, Tasks, and Variables.

Using an if statement within the parameters of a job will not work.

Examples : How to Use If Statements

Simple If Statement

If/And Statement

If/And/Or Statment

Syntax : Available If Statment Expressions

Here is a selection of the most common expressions I use regularly. For the full list, check out Microsoft's Documentation on them.

eq(parameters.version, '1.0'), eq(parameters.version, '2.0')

ne(parameters.version, '1.0')

eq(variables.version, '1.0')

contains(variables.version, '1')

startsWith(variables.version, '1')

endsWith(variables.version, '.2')

ge (Greater Than or Equal To)

ge(variables.version, 1)

gt (Greater Than)

gt(variables.version, 1)

le (Less Than or Equal To)

le(variables.version, 2)

lt (Less Than)

lt(variables.version, 2)

Recent Posts

Azure DevOps: Using Azure DevOps YAML Templates

Azure DevOps: Setting Pre-Deployment Approvals for YAML Pipelines

Azure DevOps: Choosing a Branching Strategy for Your CI/CD Pipelines

Azure DevOps Pipelines: Conditionals in YAML

In this week’s post, we are going to cover some ways to make tasks and jobs run conditionally. This will include options such as Pipeline variables to jobs that are dependent on other jobs. This post will be using a sample Azure DevOps project built over the last few weeks of posts. If you want to see the build-up check out the following posts.

yaml conditional variable assignment

Sample YAML

The following YAML is based on the YAML from the previous posts, see links above, expanded with examples of using some ways of conditionally running some task or job. This is the full file for reference and the rest of the post will call out specific parts of the file as needed.

Job Dependencies

The more complex pipelines get the more likely the pipeline will end up with a job that can’t run until other jobs have completed. The YAML above defines three different jobs, WebApp1, WebApp2, and DependentJob. I’m sure you have guessed by now that the third job is the one that has a dependency. To make a job dependent on other jobs we use the dependsOn element and list the jobs that must complete before the job in question can run. The following is the YAML for the sample DependentJob with the dependsOn section highlighted.

With the above setup, DependentJob will only run if both the WebApp1 and WebApp2 jobs complete successfully.

Conditions are a way to control if a Job or Task is run. The following example is at the job level, but the same concept works at the task level. Notice the highlighted condition .

The above condition will cause the WebApp2 job to be skipped if the BuildWebApp2 variable isn’t true. For more details on how to use conditions see the Conditions docs .

Creating a Pipeline Variable

The rest of the post is going to walk through creating a Pipeline variable and then running some sample builds to show how depends on and the conditions defined in the YAML above affect the Pipeline results.

We are starting from an existing pipeline that is already being edited. To add (or edit) variables click the Variables button in the top right of the screen.

yaml conditional variable assignment

The Variables pop out will show. If we had existing variables they show here. Click the New variable button to add a new variable.

yaml conditional variable assignment

We are adding a variable that will control the build of WebApp2 called BuildWebApp2 that defaults to the value of true . Also, make sure and check the Let user override this value when running this pipeline checkbox to allow us to edit this variable when doing a run of the pipeline. Then click the OK button.

yaml conditional variable assignment

Back on the Variables dialog click the Save button.

yaml conditional variable assignment

Edit Variables When Starting a Pipeline

Now that our Pipeline has a variable when running the Pipeline under Advanced options you will see the Variables section showing that our Pipeline has 1 variable defined. Click Variables to view/edit the variables that will be used for this run of the Pipeline.

yaml conditional variable assignment

From the Variables section, you will see a list of the defined variables as well as an option to add new variables that will exist only for this run of the Pipeline. Click on the BuildWebApp2 variable to edit the value that will be used for this run of the Pipeline.

yaml conditional variable assignment

From the Update variable dialog, you can change the value of the variable. When done click the Update button.

yaml conditional variable assignment

Pipeline Results from Sample YAML

The following is what our sample Pipeline looks like when queued with the BuildWebApp2 variable set to false. As you can see the job will be skipped.

yaml conditional variable assignment

Next is the completed results of the Pipeline run. You can see that the Build Dependent Job was skipped as well since both Build WebApp1 and Build WebApp2 must complete successfully before it will run.

yaml conditional variable assignment

Changing the BuildWebApp2 variable back to true and running the Pipeline again results in all the jobs running successfully.

yaml conditional variable assignment

Wrapping Up

Hopefully, this has helped introduce you to some of the ways you can control your Pipelines. As with everything else Azure DevOps related things are changing a lot and new options are popping up all the time. For example, while writing this post the team just announced Runtime Parameters which look like a much better option than variables for values that frequently vary between Pipeline runs.

Also published on Medium .

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pocket (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Telegram (Opens in new window)

Leave a Comment Cancel Reply

Your email address will not be published. Required fields are marked *

Notify me of follow-up comments by email.

Notify me of new posts by email.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

yaml conditional variable assignment

  • ApplicationInsights
  • Architecture
  • Architecture Castle
  • Azure Devops
  • Azure Pipelines
  • AzureDevOps
  • CodeAnalysis
  • Continuos Integration
  • Continuous Deployment
  • Continuous Integration
  • ContinuousDeployment
  • EF Code First
  • Enterprise Library
  • Entity Framework
  • EverydayLife
  • Experiences
  • GitHub Actions
  • Lab Management
  • masstransit
  • Microsoft Test Manager
  • NET framework
  • Performance
  • Power Tools
  • Process Template
  • Programming
  • Pull Requests
  • PullRequests
  • SemanticKernel
  • Silverlight
  • Software Architecture
  • Source control
  • Team Foundation Server
  • TeamFoundationServer
  • Tfs Power Tools
  • Tfs service
  • Tools and library
  • Unit Testing
  • UnitTesting
  • Virtual Machine
  • Visual Studio
  • Visual Studio 2013
  • Visual Studio ALM
  • Visual Studio Database Edition
  • VisualStudio
  • VSTSDBEdition
  • Zero Trust Security

Wrecks of code floating in the sea of internet

Azure DevOps: Conditional variable value in pipeline

Azure DevOps pipeline have tons of feature, one of the less known is the ability to declare variable conditionally.

Let’s examine a simple situation, in Azure DevOps you do not have a way to change pipeline priority, thus, if you need to have an agent always ready for high-priority builds, you can resort using more agent Pools . Basically you have N license for pipeline, so you can create N-1 agents in the default Pool and create another pool, lets call it Fast, where you have an agent installed in a High Performance machine . When you need to have a pipeline run that has high priority you can schedule to run in Fast Pool and the game is done.

Doing this is super simple thanks to Pipeline parameters, but I have another interesting scenario. I have many builds of internal libraries used by teams, then when someone publish a stable version for a library, we want this library to be complied and pushed to internal Nuget as soon as possible

Time needed to publish internal library in stable version should be low.

When you have many internal libraries, it is normal to

  • Create a branch on library repository
  • Implement a new feature with all UnitTest
  • Ask for a Pull Request
  • Close everything on main/master and use the new feature in some software

Since these are internal utility, you usually add a new feature because you have a project that needs that feature. Sometimes the feature is a simple extension method or a really simple new helper function and you really do not want to wait 1 hour because you push main/master in a moment where you have high amount of build.

The solution I want is being able to automatically schedule pipeline execution **on Fast Pool if I’m compiling main/master branch”. This flow seems to me the most natural one, lets the stable version of the code have use high priority queue, while all other checks still run on default queue where developers does not care to wait for a result.

2 3 4 5 6 7 8 9 : - name: Pool displayName: Pool used to run the pipeline default: default type: string values: - default - fast

Parameters allow the user to choose a value during manual trigger, but when the pipeline is triggered automatically by a push, default value is used , so in the above situation all runs due to push are executed into the default pipeline.

What I want is being able to choose the pool to be used based on branch name

Actually I’m used to define a variable for each parameter, so I can access everything with the usual $(VariableName) notation.

2 3 : ... pool: ${{parameters.pool}}

This allows for a really simple solution, because you can set variable values with conditions, thanks to powerful syntax of Azure DevOps pipelines . Here is the final code.

2 3 4 5 6 7 8 9 : ... - ${{ if or( eq(variables['Build.SourceBranch'], 'refs/heads/master'), eq(parameters.Pool, 'fast') ) }}: - name: Pool value: 'fast' - ${{ else }}: - name: Pool value: 'default'

The syntax could seems strange, but thanks to the ${{ if instruction I’m able to use condition directly in the yaml file . This allows me to tell the engine that, if the parameter Pool is fast or if the Build.SourceBranch is the master branch I want the value of the variable Pool to be equal to fast . Condition are evaluated before the pipeline is actually executed, and basically allows you to set part of the YAML file with condition.

YAML condition in Azure DevOps pipeline are evaluated before scheduling the run, so they are allowed to select the pool.

This is important because the engine, first of all evaluates all the conditional YAML part, then when everything was determined, it proceed to analyze YAML content, and schedule the execution on the right pool.

To diagnose what is happening, after the build is completed you can download all log in zipped format, because it contains the initializeLog.txt file that contains log of the initialization . That file is really useful because, as you can see from Figure 1, it contains all checks and condition and expansions that are done before actually executing the pipeline.

Check initialization of the pipeline

Figure 1: Check initialization of the pipeline

Then do not forget to look at the azure-pipelines-expanded.yaml files that contains the result yaml file after all expansions and conditions were evaluated . These two files are invaluable to diagnose problem when you use some advanced configuration like conditional variables.

In the end the result is obtained, each time that a run is triggered from the master branch, it will be scheduled automatically on Fast pool.

Gian Maria.

How to use variables and parameters inside your Azure DevOps YAML templates

Quick tips on how to use correctly variables inside your templates..

In the previous article we have shown you the basics of using variables inside your Azure DevOps pipelines. Today we will go further and take a look at different ways to use variables and parameters inside reusable templates.

Variables usage

For the purpose of this tutorial let us take this extract of template:

In this example, we have a basic shell task Bash@3 that calculates the build version number for our application. Because we define the minimumVersionNumber inside the default Azure DevOps variables object, there are two options to access it:

  • $(minimumVersionNumber) : This notation is accessible anywhere in your template
  • ${{ variables.minimumVersionNumber }} : This is only accessible at the same level of the variables definition

Pass parameters to a template

With that done we will create a new template inside a file called: compute-build-number.yml to be able to reuse this task in different projects:

As you can see the minVersion is defined inside the object parameters , to access it you need to use ${{ parameters.minVersion }} . You can call the object parameters the way you need, the goal is to define all parameters needed for this template to work. This will also be useful when someone else want to know the necessary parameters to provide to be able to reuse this template.

Now, let us update our pipeline to use this template:

Why do not we use the $(my_variable) notation everywhere inside our pipeline and avoid using parameters for our templates?

It is not recommended because if you do that you will:

  • Lose the general property of your templates and you will not have the ability to reuse it,
  • You will not know which parameters are needed to use the template.

Final touch

As you can see in these tutorials, you have multiple ways to use parameters and variables inside Azure DevOps, be sure to check the context to apply the right one, you do not access your variables and parameters the same way.

  • Azure DevOps

Do not hesitate to follow me on Twitter to not miss my next tutorial!

yaml conditional variable assignment

Conditionally Deploying YAML Pipelines In Azure Devops By Branch

Apologies for the absolute word soup of a title above, but I wasn’t sure how else to describe it! So instead, let me explain the problem I’ve been trying to solve lately.

Like many organizations using Azure Devops, we are slowly switching our pipelines to use YAML instead of the GUI editor. As part of this, I’ve been investigating the best way to conditionally deploy our CI build to environments. Notably, I want our CI build to run for every check in, on every branch, but only move to the “release” stage if we are building the develop branch and/or the main trunk. As we’ll find out later, there also needs to be an override mechanism for this because while it’s a general rule, it’s also something that may need to be flexed at times.

YAML pipelines documentation can be a bit shaky at times, so most of this came from trial and error, but here’s what I found to solve the problem of conditionally deploying Azure Pipelines based on a branch.

Using Environments

Your first option is to use Environments inside Azure Devops. You can add an “Approval and Check” to an environment, and then select Branch Control.

yaml conditional variable assignment

You can then specify a comma seperated list of branches that are allowed to pass this environment gate, and be deployed to the environment :

yaml conditional variable assignment

But here’s the problem I had with this approach. Environment gates such as the above are not in source control. Meaning that it’s hard to roll out across multiple projects at once (Compared to copy and pasting a YAML file). Now that’s a small issue, but the next one is a big one for me.

These checks based on a branch actually *fail* the build, they don’t “skip” it. So for example, if a branch does not match the correct pattern, you will see this :

yaml conditional variable assignment

This can be incredibly frustrating on some screens because it’s unclear whether your build/release pipeline actually failed, or it just failed the “check”. There is also no way to override this check on an adhoc basis. Maybe that’s something you desire, but there are rare cases where I actually need to deploy a feature branch to an environment to test something, and going through the GUI to disable branch control, release, then add it back just doesn’t make sense.

Using Pipeline Variables

A more explicit way I found to control this was to use variables inside the YAML itself. For example, every project of mine currently has the following variables utilized :

Now anywhere in my pipeline, I can use either variables.isPullRequest or variables.isDevelopment and make conditional deployments based on these. For example, I can edit my YAML to read like so for releasing to my development environment :

This basically says, the previous steps must have succeeded *and* we must be using the development branch. When these conditions are not met, instead of a failure we see :

yaml conditional variable assignment

This is so much nicer than a failure and actually makes more sense given the context we are adding these gates. I don’t want the CI build to “fail”, I just want it to skip being released.

Adding Overrides

Remember how earlier I said that on occasion, we may want to deploy a feature branch even though it’s not in develop? Well we can actually add an override variable that when set, will push through the release.

First we must go to our YAML pipeline in Azure Devops , and edit it. Up the top right, you should see a button labelled Variables. Click it and add a new variable called “forceRelease” like so :

yaml conditional variable assignment

Unfortunately, we have to do this via the GUI for every build we wish to add this variable. At this time, there is no way to add it in the YAML and have Azure Devops recognize it (But there is hope for the future!).

In our YAML, we don’t need to declare the variable ourselves, instead it’s just available for use immediately. We can just modify our Development stage to look like so :

Now we are saying, if the branch is development or the variable forceRelease is set to true, then push through the release. If we try and kick off a build, we can now set the runtime variable at build time to push things through, no matter the branch.

yaml conditional variable assignment

Related Posts

  • Static Website Hosting With Azure Blob Storage
  • Tips For Passing AZ-900 Azure Fundamentals Exam
  • Website Hosting With Amplify Console
  • Setting Up CORS With Azure API Manager

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • Privacy and Security
  • Terms of Use

Azure DevOps Experimentation - YAML Conditionals, Parameters, and Triggers

yaml conditional variable assignment

Snippets of common questions and issues from Azure Pipeline workshops and support calls. Today's snippet includes conditionals, parameters, and triggers.

If you are an avid user of the YAML-based Azure Pipelines, you will be aware that the language can be very pedantic when it comes to too many or too few spaces. In fact, we have been mulling over a broken pipeline for (what felt like) hours, only to realise that we were misaligned by one space. Fortunately, both the YAML editor in both Azure DevOps and Visual Studio Code, as well as the Validate features are continuously improving.

Let us park the spaces topic and focus on conditionals, parameters, and triggers, using this simple sample code.

Experimentation Sample Code

You can configure a trigger to fire manually , never , or as changes are made to selected branches, tags, and folders.

  • If you remove the trigger all together, the pipeline will be triggered if any change is made to any folder or branch .
  • If you want to have a manually triggered pipeline, you must configure - none , as in today's sample code.

See Triggers for details.

You can use parameters in templates and pipelines, as visualised on our YAML Generic Blueprint-based Pipeline Quick Reference and documented in detail in the YAML Schema .

  • Parameter key:value pairs are evaluated at queue time.
  • You can define a pipeline parameter, as in the sample code above.
  • When you run the sample pipeline, you can select from the available values, as shown:

See Parameters for details.

You can add static values, reference variable groups, or insert variable templates into your pipeline.

  • Variable key:value pairs are evaluated at run time.
  • Echo 1 is boring, but we must say hello!
Output: keyFinal .
Output: Bingo!

See Variables for details.

Conditionals

Lastly, conditions can be used to determine whether tasks should execute or if code or entire template are injected into the pipeline at queue time.

  • # Lower demonstrates how to include tasks if certain conditions are met. In our sample, we check if the selected parameters.branch is equal to 'release'. If yes, Bingo!
  • Note how we convert the parameter to lowercase before doing the comparison, so that any combination of casing for release will meet the condition.
  • Release only demonstrates how to include tasks if and only if the origin source branch matches refs/heads/release or starts with refs/heads/release/ .

We make extensive use of conditions in our blueprints and re-usable toolkit templates.

See Expressions for details.

We are done for today.

Hope these snippets are adding value and looking forward to your candid feedback. See you in the next experiment.

  • WorkSafeBC IT is hiring
  • ATOM/RSS Feed

Copyright  | Terms and Conditions

  • devops (51)
  • journal (7)
  • azure-devops (73)
  • pipelines (52)
  • engineering (43)
  • ceremony (8)
  • posters (10)
  • quality (19)
  • learning (40)
  • automation (18)
  • code-quality (13)
  • eliminate-waste (23)
  • standards (1)
  • technical-excellence (17)
  • water-cooler (2)
  • innovation (7)
  • testing (15)
  • release (1)
  • x-as-code (16)
  • version-control (4)
  • metrics (3)
  • continuous-delivery (2)
  • delivery-on-demand (2)
  • architecture (5)
  • collaboration (2)
  • team-building (1)
  • no-estimates (1)
  • estimates (2)
  • strategy (1)
  • planning (1)
  • process (2)
  • customer-centric (1)
  • psychological-safety (1)
  • testability (1)
  • system-programming (1)
  • security (1)
  • feature-flags (3)
  • workflow (1)
  • Events (10)
  • Posts (186)

Andrew Hoefling

  • Recent Talks

Andrew Hoefling

yaml conditional variable assignment

Microsoft MVP DNN MVP Xamarin Certified

I'm Andrew Hoefling, and I work for FileOnQ as a Lead Software Engineer building mobile technologies for Government, Financial and First Responders using Xamarin. 

yaml conditional variable assignment

Conditional Insertion in Azure Pipelines

Using Conditional Insertion in Azure Pipelines allows a build to insert tasks depending on parameters. This differs than a conditional task becaues it can remove or add the task to the build task list. This means you can completely customize the build tasks and only show the ones that the build is interested in.

Conditional Tasks != Conditional Insertion

When defining project builds for Azure Pipelines it is common to have tasks run if a certain criteria is true. This technique is called conditions and it can be applied to any task. Some options available in a condition are:

  • Prevent task from running
  • Run task even if build failed
  • Allow task to run if a criteria is true

In all cases with Conditions the build task still shows up in the build history. When building large yaml builds this can create a lot of noise that will make it difficult to debug the problem.

Standard Condition Example

What is Conditional Insertion?

Conditional Insertion uses a similar expression syntax as a standard Task Expression, with one major exception. If the statement evaluates to false the task is not added to the build task list. This means the task will only show up if the expression evaluates to true.

The syntax is a little tricky to get right

Conditional Insertion uses the  ${{ }} notation and is a little confusing at first glance. It is adding code flow to yaml which combines a couple different paradigms: configuration files and code. It is best to think of conditional insertion as an if statement inside of your build task list.

  • Azure DevOps Conditional Insertion Docs

The most basic example provided by the microsoft docs is changing a variable based on a conditional insertion. See the code snippet below:

Breaking this syntax down the actual expression is

Let's analyze the different components that make up a conditional insertion statement

Open and Closing braces

  • Closing colon

Anytime you attempt to access parameters or the code flow of Azure Pipelines yaml files you use the ${{ }} . Conditional Insertions are no different with one major exception

Boolean Expression

To implement the Conditional Insertion you will need to add an if statement into the code block. The rules can match identically to the Condtion that you have used in the past. The major difference is you need to explicitly list out the if command and then your boolean expression.

Closing Colon

This is the most important part of Conditional Insertion without it your yaml files will fail with little explanation. After the opening and closing braces ${{ }} you will need to include colon : which tells the build system to only insert the next statement if the expression evaluates as true.

Let's compare 2 different conditional statements:

Valid Expression

  Invalid Expression  - missing trailing colon

Add Condtional Task

Let's look at how we can apply this concept to a build script to conditionally add tasks. Then we can look at the build output to demonstrate when a task is added to the build task list and when it is not. Before we learned using the ${{ }} code block we can conditionaly insert statements into a yaml file. This same concept can be applied to tasks with a few changes and proper indenting.

Consider the following yaml file that has 2 tasks that run a script to print a message to the console.

Let's add a parameter to the script that will determine if the 2nd task will execute or not.

Before we add the Conditional Insertion you need to be aware that of a couple rules

  • All task statements start with a  -
  • All statements following the Conditional Insertion is indented 2 spaces

Putting all of this together we can update our 2nd task as follows

Now putting the entire script together

Troubleshooting

Creating builds with yaml is powerful and confusing, you are bound to run into an error that has no explanation. Below are some tips that may help you get through issues you run into.

Missing Dash

If you are using Conditional Insertion for a task you must have a - leading the statement otherwise the build will not work. The steps definition in your build expects an array of items the - syntax tells the build system that you are evaluating a new item in the array.

Missing Trailing Colon

All Conditional Insertion statements must end with a colon : . The colol tells the build system that the next line will be inserted if the expression evaluates to true.

Invalid Spacing

The infamous spacing of yaml files has caused hours upon hours of frustration for developers. Conditional Insertion adds potential problems with spacing. All statements after the expression must have an additional 2 spaces.

You should have the knowledge to add statements conditionally to your build yaml file using Conditional Insertion. This can be applied to parameters, variables, steps and more. If you want to see a working example, checkout my code sample on GitHub

  • https://github.com/ahoefling/Conditional-Insertion

- Happy Coding

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Support for wild cards and conditional expressions in YAML pipeline files

  • 2 contributors

In this sprint, we included support for wild cards and conditional expressions to YAML pipeline files. In addition, we've made multiple updates to the Azure Pipelines hosted images.

Check out the following feature descriptions for details.

Azure Pipelines

New yaml conditional expressions, support for wild cards in path filters, support for multiple statuses in bitbucket, allow contributors to skip seeking pr comments prior to build validation, windows server 2022 with visual studio 2022 is now available on microsoft-hosted agents (preview).

  • General availability of macOS 11 Big Sur on Microsoft-hosted agents

Removal of Ubuntu 16.04 image on Microsoft-hosted agents

Azure repos, new tfvc pages are generally available, configure branch creators to not get "manage permissions" on their branches, prevent fork users from voting on their upstream prs.

Writing conditional expressions in YAML files just got easier with the use of ${{ else }} and ${{ elseif }} expressions. Below are examples of how to use these expressions in YAML pipelines files.

Wild cards can be used when specifying inclusion and exclusion branches for CI or PR triggers in a pipeline YAML file. However, they can't be used when specifying path filters. For instance, you can't include all paths that match src/app/**/myapp* . This has been pointed out as an inconvenience by several customers . This update fills this gap. Now, you can use wild card characters ( ** , * , or ? ) when specifying path filters.

Azure Pipelines integrates with Bitbucket repositories and supports CI and PR triggers. You can set up multiple pipelines from a single Bitbucket repository. However, when these pipelines were complete, you could only see one status in Bitbucket. We heard feedback from the Developer Community asking to view the status of each pipeline separately in Bitbucket. With this update, we updated our API calls to Bitbucket and pass additional information about the name of the pipeline.

Build status

When using Azure Pipelines with GitHub repositories, we recommend that you don't automatically run a PR validation pipeline for contributions received from a forked repository. The best practice here's to first have one of the collaborators of the repository review the change and then add a comment to the PR to trigger the pipeline. You can configure these settings by selecting the Triggers menu (for YAML pipelines) or the Triggers tab (for classic build pipelines) in the pipeline web editor. Instead of requiring every PR from a fork to be first reviewed by a team member, you can also enforce this policy only on contributions that originate from non-team members.

With this update, we're allowing you to skip seeking a PR comment from contributions received by any contributor. As a non-team member, when you create a fork and create a PR to the upstream, you aren't considered a contributor to the upstream repository until your PR is merged. Once your PR is merged, you'll be considered a contributor. By selecting the new option shown below, when a non-team member submits a PR from a fork for the first time, someone on your team would have to review the PR and add a comment to trigger the pipeline. But, once the PR is merged, any further contributions made by that non-team member will directly trigger the pipeline without waiting for a PR comment.

Require a team member's comment before building a pull request

Windows Server 2022 and Visual Studio Enterprise 2022 Preview are now available in preview on Microsoft-hosted agents. You can use it by referencing windows-2022 as image in your pipeline.

When you reference windows-latest pool in your YAML pipelines, it will still mean windows-2019 and not windows-2022, while the latter is in preview.

The Windows Server 2022 pipeline image has different tools and tool versions when compared to Windows Server 2019. You can see the details in the software announcement issue and in the documentation virtual-environments repository .

General availability of macOS 11 on Microsoft-hosted agents

macOS 11 is now generally available on Microsoft-hosted agents. You can use it by referencing macos-11 as image in your pipeline.

As announced earlier , we'll be removing Ubuntu 16.04 image from Microsoft-hosted agents on September 20, 2021. Traditional 5-years support of Ubuntu 16.04 by Canonical ended in April, 2021. You'll need to migrate ubuntu-16.04 pipelines to ubuntu-18.04 or ubuntu-latest which will run on Ubuntu 20.04 LTS.

Builds that use Ubuntu-16.04 already have a warning being logged in them. To make sure everyone is aware of this change, we scheduled 2 short "brownouts". Ubuntu 16.04 builds will fail during the brownout period. Therefore, it's recommended to migrate your workflows prior to the September 6, 2021.

The brownouts are scheduled for the following dates and times (Note that these have been extended by an hour from the earlier announced times): September 6, 2021 4:00pm UTC – 10:00pm UTC September 14, 2021 4:00pm UTC – 10:00pm UTC

We have been updating various pages in Azure DevOps to use a new web platform with the goal of making the experience more consistent and more accessible across the various services. TFVC pages have been updated to use the new web platform, and those changes have been in preview for several months now. With this update, we are making the new TFVC pages generally available. With this update, you will no longer see a preview feature called "New TFVC pages" in their user settings.

When you create a new branch, you get "Manage permissions" on that branch. This permission lets you change the permissions of other users or admit additional users to contribute to that branch. For instance, a branch creator may use this permission to allow another external user to make changes to the code. Or, they may allow a pipeline (build service identity) to change the code in that branch. In certain organizations with higher compliance requirements, users should not be able to make such changes.

With this update, you can configure any and all repositories in your team project and restrict branch creators from getting the "Manage permissions" permission. To do this, navigate to the project settings, select Repositories, and then Settings for all repositories or a specific repository.

All repositories settings

This setting is on by default to mimic the existing behavior. But, you can turn it off if you wish to make use of this new security feature.

With Azure Repos, users with "read" permission on a repository can fork the repo and make changes in their fork. To submit a pull request with their changes to the upstream, users need "contribute to pull requests" permission on the upstream. However, this permission also governs who can vote on pull requests in the upstream repository. As a result, you can end up in situations where a user, who is not a contributor to the repository, can submit a pull request and cause it to be merged depending on how you set up the branch policies.

In organizations that promote an inner-source model, fork-and-contribute is a common pattern. To secure and promote this pattern further, we are changing the permission to vote on a pull request from "contribute to pull requests" to "contribute". However, this change is not being made by default in all organizations. You have to opt-in and select a new policy on your repository, called "Strict Vote Mode" to switch this permission. We recommend that you do so if you rely on forks in Azure Repos.

Repository settings

These features will roll out over the next two to three weeks.

Head over to Azure DevOps and take a look.

Go to Azure DevOps

How to provide feedback

We would love to hear what you think about these features. Use the help menu to report a problem or provide a suggestion.

Make a suggestion

You can also get advice and your questions answered by the community on Stack Overflow .

Aaron Hallberg

Was this page helpful?

Additional resources

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

If condition possible in yaml file?

I need to add one more name based on if condition. If If variable value from another .yml file is "yes" then add a new name in the list

I've the following code in my yaml file:

I need to add more name based on if condition. If variable value from another .yml file is "yes" then add a new name like this:

is this possible?

Tried the following:

Anthon's user avatar

  • 2 Not with "just" YAML. YAML is akin to HTML or JSON in this regard: see the YAML specification for what is allowed. –  user2864740 Commented Jan 15, 2019 at 7:09
  • I suggest you read up on YAML (the specfication, the yaml.org website). 1) The recommended extension for YAML files has been .yaml since 2006. 2) You seem to be under the illusion that literal block style scalars are interpreted by YAML. There is nothing in the specification even hinting at that (what your program does is of course a different matter). 3) You seem to think YAML has some dotted notation to get to nested values. Again read the spec it doesn't. –  Anthon Commented Jan 15, 2019 at 19:24

7 Answers 7

As a supplement to Vaibhav's response: although yml does not inherently support if statements, some applications that use yml files for instructions may be able to parse if statements included in the yml. GitLab is one notable example. In GitLab's CI/CD, the .gitlab-ci.yml file can be configured to include if statements such as:

This is from https://docs.gitlab.com/ee/ci/yaml/#rules .

For more info, see this answer: https://stackoverflow.com/a/55464100/10792235 .

Chris Collett's user avatar

  • What about a bash script in the yml file? What's the right format? I've got a question here, trying to solve it for a long time, could you take a look please stackoverflow.com/questions/65214195/… –  wawawa Commented Dec 9, 2020 at 9:59
  • Your question was removed, but you would add a - script: section and put your code into it. Each line should start with a dash. Sometimes you may need to enclose the line in quotes for certain characters to be read. –  Chris Collett Commented Jan 7, 2021 at 22:01

You can't add conditions to a yml file its just a text formatting way, not a language. But still, you can load the yml file into a programming language and can apply if else to it. based on a string.

vaibhav lodha's user avatar

  • 2 Thanks a million for the reply, I would be thankful to you if Could you please gimme an example? and how to add yml file into a programming language? –  Muhammad Umair Commented Jan 15, 2019 at 7:15
  • check this post : stackoverflow.com/questions/41974628/… –  vaibhav lodha Commented Feb 4, 2019 at 7:53
  • 1 That's not true. inmy code for instance I use following code nagiosgroup: "{{ 'srv-test' if inventory_hostname in groups['KISS_ACPT'] else 'srv-dev' }}" –  Thibault Richard Commented Sep 24, 2020 at 14:57
  • 1 That's not true. inmy code for instance I use following code vartodefine: "{{ 'value1' if inventory_hostname in groups['BLAH'] else 'value2' }}" –  Thibault Richard Commented Sep 24, 2020 at 14:58
  • I wanted to run a bash script inside yaml, can you take a look at this question please? stackoverflow.com/questions/65214195/… –  wawawa Commented Dec 9, 2020 at 9:58

Abrahim's user avatar

An elegant option, when having multiple configuration files would be as follows:

application.yml

application-qa.yml

application-prod.yml

Radu Linu's user avatar

  • Is this even a thing? It didn't work for me at least in Azure pipelines yaml –  Julian Dominguez Commented Jul 15, 2022 at 15:37

Please try below syntax for condition in Yaml file

Nikhil's user avatar

Try this code, the word "item" could be whatever you want:

Thylorion's user avatar

  • which library would be able to support this in python? I tried the default pyyaml, it shows error while parsing % found character '%' that cannot start any token –  Rohit Dwivedi Commented Jul 21, 2021 at 11:46

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged yaml or ask your own question .

  • The Overflow Blog
  • Mobile Observability: monitoring performance through cracked screens, old...
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Do passengers transiting in YVR (Vancouver) from international to US go through Canadian immigration?
  • Is it a date format of YYMMDD, MMDDYY, and/or DDMMYY?
  • Is there a way to have GeoServer store it's configuration in a database instead of XML files
  • What does the equation of the law of conservation of total mechanical energy with deformation energy look like?
  • Functor composition rule necessary?
  • Removing duplicate data based on multiple attributes
  • Best way to explain the thinking steps from x² = 9 to x=±3
  • If you switch to a non-orthogonal basis, are vectors that were previously orthogonal still orthogonal?
  • Doesn't counting hole and electron current lead to double-counting of actual current?
  • What would happen if the voltage dropped below one volt and the button was not hit?
  • A classic problem about matrix
  • Took a pic of old school friend in the 80s who is now quite famous and written a huge selling memoir. Pic has ben used in book without permission
  • When to use negative binomial and Poisson regression
  • How can I Align an existing Object to the 3D Viewport's XY Plane?
  • Does a held action have to be an action?
  • Why does my shifter say the wrong gear?
  • Bash script that takes multiple path arguments and checks if files can be successfully created there
  • Which Mosaic law was in the backdrop of ceremonial hand-washing in Mark 7?
  • Which version of Netscape, on which OS, appears in the movie “Cut” (2000)?
  • How is an inverting opamp adder circuit able to regulate its feedback?
  • What does this translated phrase convey "The heart refuses to obey."?
  • What does "if you ever get up this way" mean?
  • How specific does the GDPR require you to be when providing personal information to the police?
  • If you have two probabilities, how do you describe how much more likely one is than the other?

yaml conditional variable assignment

IMAGES

  1. Azure Pipelines (yaml) using conditional to set a new variable

    yaml conditional variable assignment

  2. YAML tutorial

    yaml conditional variable assignment

  3. YAML in a nutshell

    yaml conditional variable assignment

  4. azure pipelines

    yaml conditional variable assignment

  5. Conditional Statements in Java (If-Else Statement)

    yaml conditional variable assignment

  6. Yaml tutorial specification rules and syntax

    yaml conditional variable assignment

VIDEO

  1. Operators, Conditional statements, Variable, global variable,#basics #php #programminglanguage

  2. 6 storing values in variable, assignment statement

  3. S1 RANDOM VARIABLE

  4. Conditional and selected signal assignment statements

  5. Variable Assignment in R

  6. Ansible-playbook -- YAML Scripting

COMMENTS

  1. yaml

    As an extension to @Mike Murray's answer, if you are using variable groups you must define additional variables as name value pairs. To use conditional variable assignment in this case would be as follows:

  2. how can I use IF ELSE in variables of azure DevOps yaml pipeline with

    I'm trying to assign one of 2 values to a variable in addition to variable group and can't find the reference that how to use IF ELSE. ... Writing conditional expressions in YAML files just got easier with the use of ${{ else }} and ${{ elseif }} expressions. ... I think for now you're going to need to use a task to customize with name/value ...

  3. Conditional Variables in Azure DevOps Pipelines

    script: |. echo ${{variables.teamName}} Lets run the pipeline, as mentioned above - The parameter "environment", will be asked at run-time. Reviewing the task output in Azure DevOps. We can see the variable it uses is beta, the conditional for parameter.environment preproduction! 1. 2. ${{ if eq( parameters['environment'], 'preproduction ...

  4. Define variables

    When you define a variable at the top of a YAML, the variable is available to all jobs and stages in the pipeline and is a global variable. ... both variable and conditional variable syntax will differ. For information about the specific syntax to use, see Deployment jobs ... When you create a multi-job output variable, you should assign the ...

  5. Azure DevOps Pipelines: If Expressions and Conditions

    This post will attempt to cover some basics around using if and conditions in your YAML Pipelines. If Expressions. If expressions are simple and easy enough in YAML pipelines, they are a powerful tool. In my experience I have leveraged if expressions to: Conditionally load templates Dynamically load variables Enable same pipeline for CI/CD

  6. Expressions

    Runtime expressions are intended as a way to compute the contents of variables and state (example: condition ). # Two examples of expressions used to define variables # The first one, a, is evaluated when the YAML file is compiled into a plan. # The second one, b, is evaluated at runtime. # Note the syntax ${{}} for compile time and $[] for ...

  7. Pipeline conditions

    This condition is the default if no condition is set in the YAML. Even if a previous dependency fails, unless the run is canceled. Use succeededOrFailed() in the YAML for this condition. Even if a previous dependency fails, and even if the run is canceled. Use always() in the YAML for this condition. Only when a previous dependency fails.

  8. If, elseif or else in Azure DevOps Pipelines

    Determining which variable to use; Determining which task to run; Determining which stage to run; if, elseif or else expressions to determine which variable to use. Lets have a look at using these conditional expressions as a way to determine which variable to use depending on the parameter selected.

  9. Azure DevOps: If Statements in Your YAML Pipelines

    If Statements are a fantastic feature in YAML pipelines that allows you to dynamically customize the behavior of your pipelines based on the parameters you pass. They use syntax found within the Microsoft Conditions Documentation. Let's dive in and talk about how you can add them to your pipelines. Constraints: Where You Can Use If Statements.

  10. Azure DevOps Pipelines: Conditionals in YAML

    To add (or edit) variables click the Variables button in the top right of the screen. The Variables pop out will show. If we had existing variables they show here. Click the New variable button to add a new variable. We are adding a variable that will control the build of WebApp2 called BuildWebApp2 that defaults to the value of true.

  11. Azure DevOps: Conditional variable value in pipeline

    The syntax could seems strange, but thanks to the ${{ if instruction I'm able to use condition directly in the yaml file.This allows me to tell the engine that, if the parameter Pool is fast or if the Build.SourceBranch is the master branch I want the value of the variable Pool to be equal to fast.Condition are evaluated before the pipeline is actually executed, and basically allows you to ...

  12. How to use variables and parameters inside your Azure DevOps YAML

    With that done we will create a new template inside a file called: compute-build-number.yml to be able to reuse this task in different projects: # compute-build-number.yml # Define parameter first way: parameters: minVersion: 0 # Or second way: parameters: - name: minVersion type: number value: 0 steps: - task: Bash@3 displayName: 'Calculate a ...

  13. Azure DevOps Pipelines: If Expressions and Conditions

    Conditions. A condition is actually a key word defined in the schema of any stage, job, or step. It's not always documented; however, it is available. Microsoft defines conditions as: You can specify the conditions under which each stage, job, or step runs. By default, a job or stage runs if it doesn't depend on any other job or stage, or if ...

  14. Conditionally Deploying YAML Pipelines In Azure Devops By Branch

    First we must go to our YAML pipeline in Azure Devops, and edit it. Up the top right, you should see a button labelled Variables. Click it and add a new variable called "forceRelease" like so : Unfortunately, we have to do this via the GUI for every build we wish to add this variable.

  15. Azure DevOps Experimentation

    Variables. You can add static values, reference variable groups, or insert variable templates into your pipeline. Variable key:value pairs are evaluated at run time. Echo 1 is boring, but we must say hello! Echo 2 displays the value of keyTest, which was set to the same value as keyRef. Output:keyFinal. Echo 3 is the one that is a bit more ...

  16. Template expressions

    You can use template expressions to alter the structure of a YAML pipeline. For instance, to insert into a sequence: ... You can also use conditional insertion for variables. In this example, start always prints and this is a test only prints when the foo variable equals test. variables: - name: foo value: test pool: vmImage: 'ubuntu-latest ...

  17. Conditional Insertion in Azure Pipelines

    It is adding code flow to yaml which combines a couple different paradigms: configuration files and code. It is best to think of conditional insertion as an if statement inside of your build task list. Azure DevOps Conditional Insertion Docs; The most basic example provided by the microsoft docs is changing a variable based on a conditional ...

  18. Support for wild cards and conditional expressions in YAML pipeline

    Support for wild cards in path filters. Wild cards can be used when specifying inclusion and exclusion branches for CI or PR triggers in a pipeline YAML file. However, they can't be used when specifying path filters. For instance, you can't include all paths that match src/app/**/myapp*.

  19. If condition possible in yaml file?

    fi. I need to add more name based on if condition. If variable value from another .yml file is "yes" then add a new name like this: - name: 'jquery.min.js'. - name: 'script.js'. - name: 'new.js'. Not with "just" YAML. YAML is akin to HTML or JSON in this regard: see the YAML specification for what is allowed.