Skip to content

Instantly share code, notes, and snippets.

@murphyslaw
Created May 18, 2024 18:33
Show Gist options
  • Save murphyslaw/ce87b9ae9d0fe583763f7a596eef2973 to your computer and use it in GitHub Desktop.
Save murphyslaw/ce87b9ae9d0fe583763f7a596eef2973 to your computer and use it in GitHub Desktop.
[Bitbucket Pipeline] Handle a repository-dependent dynamic step environment variable with default value from package.json version

PROBLEM

When, for example, you are sharing a step between a custom and a branch pipeline which requires a variable to be set, then you can set this variable in the custom pipeline with a custom manual pipeline variable , but this leaves the variable unset in the branch pipelines.

SOLUTION

If the VERSION variable is a static value in the branch pipelines, you can set it in the workspace , deployment or repository variables configuration. But if it is a dynamic value, based on your repository content, then shell parameter expansion allows to set a default based on a command when the variable is empty or null.

EXAMPLE

In the example bitbucket-pipelines.yml, the "deploy" step uses the mandatory VERSION variable. The custom pipeline "manual-deploy" sets this variable by using a custom manual pipeline variable, even with a default of latest, which is displayed in the Bitbucket GUI . The branch pipeline "main" cannot set the variable. Because of the package.json file with a "version" key set in the repository, which will be used as a default.

  • In the "deploy" step, the VERSION variable is set to the version defined in the package.json file, when it is empty or null.
  • The ":" colon null utility prevents executing the result of the expansion.
  • The "jq" tool is part of the Atlassian default image .
  • The "--raw-output" option removes quotes from the returned JSON string.
  • The ".version" object identifier-index filter returns the value at the JSON object key "version".
image: atlassian/default-image:4
definitions:
steps:
- step: &deploy
name: 'Deploy Application'
script:
- : ${VERSION:=$(jq --raw-output '.version' package.json)}
- echo ${VERSION}
pipelines:
custom:
manual-deploy:
- variables:
- name: VERSION
default: latest
- step: *deploy
branches:
main:
- step: *deploy
{
"version": "1.2.3"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment