How to write conditional statements in bitbucket pipelines.yml file?

Viewed 6867

I am new to bitbucket pipelines and trying to deploy my code via bitbucket pipelines by using javaScript. My question is can we declare variables like (ex: var flag = false) and then write if/else statements based the flag value.

Below is my pipelines.yml file

# This is a sample build configuration for JavaScript.
# Check our guides at https://confluence.atlassian.com/x/14UWN for more examples.
# Only use spaces to indent your .yml configuration.
# -----
# You can specify a custom docker image from Docker Hub as your build environment.
image: node:12.18.2

pipelines:
branches: # deploying as per branches
 feature/pocDepTerex: # poc master branch
    - step: 
       caches:
        - node
       script: 
         - node -v

Here, I want to declare a flag and run the script node -v only when the flag is true.

Please let me know if there is any way to do it in pipelines

2 Answers

You sure can! Whilst you're probably used to writing a series of one-line commands in bitbucket-pipelines.yml, you can use standard YAML syntax to insert multiline content. For example:

image: node:12.18.2

pipelines:
branches: # deploying as per branches
 feature/pocDepTerex: # poc master branch
    - step: 
       caches:
        - node
       script: 
         - export MY_FLAG=true
         - |
           if [ "$MYFLAG" = true ]; then
             node -v
           fi

Full disclosure: I work for Atlassian, though not on the Bitbucket Pipelines team :)

The answer posted by daveruninseverything works perfectly fine when the steps involved are shell-type commands but not helpful when Bitbucket pipes are being used. (For more information on Bitbucket pipes click here)

Following line can be added just before an execution of Bitbucket pipe as shown below in order to implement a conditional:

- if [ "$BITBUCKET_WORKSPACE" != test ]; then exit 0 ; fi
- pipe: atlassian/aws-s3-deploy:0.2.4

The above added lines ensure that the pipe will be executed only if the workspace name is test.

Related