I'm using gitLab CI for my nodejs application. In my YML file I need to call a script to build a docker image. But instead of using latest
I need to use the current version of the project.
This version value can be find in the package.json
file of the repository.
Is it possible to read the version value of the package.json file to replace latest
by the current version?
# ...
variables:
CONTAINER_RELEASE_IMAGE: $CI_REGISTRY_IMAGE:latest # need version value instead of latest
build:
stage: build
script:
# ...
- cd /opt/core/bundle && docker build -t $CONTAINER_RELEASE_IMAGE .
- docker push $CONTAINER_RELEASE_IMAGE
Your package. json holds important information about the project. It contains human-readable metadata about the project (like the project name and description) as well as functional metadata like the package version number and a list of dependencies required by the application.
json . The dependencies in your project's package. json allow the project to install the versions of the modules it depends on. By running an install command inside a project, you can install all of the dependencies listed in the project's package.
The keywords property inside a package. json file is, as you may have guessed, a collection of keywords about a module. Keywords can help identify a package, related modules and software, and concepts.
To use variable, you need to declare a section named config (or something else, but not a name was already taken by the package. json ). And in this section, you can declare ALL YOUR VARIABLES : { ... "config": { "path": ".
I would argue the easiest way to retrieve version
from your package.json
is to use node itself.
build:
stage: build
script:
- export VERSION=$(node -p "require('./package.json').version")
- export CONTAINER_RELEASE_IMAGE=$CI_REGISTRY_IMAGE:$VERSION
- cd /opt/core/bundle && docker build -t $CONTAINER_RELEASE_IMAGE .
- docker push $CONTAINER_RELEASE_IMAGE
The -p
/--print
flag means evaluate the expression and print the result. It's functionally equivalent to using the -e
/--eval=
flag and wrapping the expression in console.log(...)
.
If you are not against installing additional packages you can use jq
which allows for much more flexibility (available in repository for both Ubuntu and Alpine).
Once you install it (for example apt-get update && apt-get install -yqq jq
on Ubuntu):
- export VERSION=$(jq -r .version package.json)
- cd /opt/core/bundle && docker build -t $CI_REGISTRY_IMAGE:$VERSION .
- docker push $CI_REGISTRY_IMAGE:$VERSION
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With