Get value of package.json in gitLab CI YML

我们两清 提交于 2020-01-01 08:56:22

问题


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

回答1:


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=$(cat package.json | jq -r .version)
- cd /opt/core/bundle && docker build -t $CI_REGISTRY_IMAGE:$VERSION .
- docker push $CI_REGISTRY_IMAGE:$VERSION



回答2:


variables:

PACKAGE_VERSION: $(cat package.json | grep version | head -1 | awk -F= "{ print $2 }" | sed 's/[version:,\",]//g' | tr -d '[[:space:]]')  `

in your job or template

.package-template: &package_template 
image: docker-hub.registry.integ.fr.auchan.com/docker:latest
stage: package 
tags: 
  - stocks
script:
  - export VERSION= ``eval $PACKAGE_VERSION``
  - echo "======> Getting VERSION:  $VERSION" `



回答3:


You might not be able to do this purely in the gitlab.yml unfortunately, you could create a shell script as follows and check this into your source control

#!/bin/sh
args=("$@")
CI_REGISTRY_IMAGE=${args[0]}

PACKAGE_VERSION=$(cat package.json \
| grep version \
  | head -1 \
  | awk -F: '{ print $2 }' \
  | sed 's/[",]//g' \
  | tr -d '[[:space:]]')
CONTAINER_RELEASE_IMAGE=$CI_REGISTRY_IMAGE\:$PACKAGE_VERSION
cd /opt/core/bundle && docker build -t $CONTAINER_RELEASE_IMAGE .
docker push $CONTAINER_RELEASE_IMAGE

Then execute this script with the argument of $CI_REGISTRY_IMAGE in gitlab.yml

# ...
build:
  stage: build
  script:
    # ...
    - chmod +x script.sh
    - ./script.sh $CI_REGISTRY_IMAGE

To the best of my knowledge this should work for you.

Thank you to DarrenN and dbaba on Github for his package.json version extract shell function



来源:https://stackoverflow.com/questions/43165840/get-value-of-package-json-in-gitlab-ci-yml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!