Charles Morin
Charles Morin

Reputation: 1447

How to read Maven POM from GitLab CI/CD pipeline stage?

I have the following .gitlab-ci.yml file, and I'd like to leverage the Maven POM to get the artifact version and use it upon calling the Artifactory REST API.

image: maven:3-jdk-8

stages:
- build
- test
- quality-scan
- quality-gate
- publish

before_script:
  - echo "Start of CI/CD Pipeline"

Build:
  stage: build
  tags: 
    - maven
  artifacts:
    paths:
      - target/
  script:
    - echo "Cleaning workspace, compiling and packaging the application"
    - mvn clean package -DskipTests

RunTests:
  stage: test
  tags: 
    - maven
  script:
    - echo "Running tests"
    - mvn test

StaticCodeAnalysis:
  stage: quality-scan
  tags: 
    - maven
  dependencies:
    - Build
  script:
    - echo "Running SonarQube analysis"
    - mvn sonar:sonar -Dsonar.host.url=$SONARQUBE_URL

QualityGateCheck:
  stage: quality-gate
  tags: 
    - maven
  script:
    - echo "Checking Quality Gate"

PublishBinary:
  stage: publish
  tags: 
    - maven
  dependencies:
    - Build
  script:
    - echo "Publishing to Artifactory"
    - export PROJECT_VERSION=mvn -o help:evaluate 
    - export ARTIFACTORY_PUBLISH_LOCATION="$ARTIFACTORY_URL/libs-release-local/$CI_PROJECT_PATH/$PROJECT_VERSION/$CI_PROJECT_NAME-$PROJECT-VERSION.jar"
    - echo $ARTIFACTORY_PUBLISH_LOCATION
    - curl -u $ARTIFACTORY_USER:$ARTIFACTORY_PASSWORD -X PUT $ARTIFACTORY_PUBLISH_LOCATION -T $CI_PROJECT_NAME


after_script:
  - echo "End of CI/CD Pipeline"

Is there an easy way to do this in GitLab CI/CD?

I use the latest version of GitLab and GitLab Runner. Both on Ubuntu hosted in an Azure Cloud.

Upvotes: 1

Views: 5358

Answers (2)

ololoid
ololoid

Reputation: 109

jobname:
  stage: stage
  before_script:
    - export "MAVEN_ID=$(mvn help:evaluate -Dexpression=project.id -q -DforceStdout)"
    - >
      IFS=: read -r MAVEN_GROUPID MAVEN_ARTIFACTID MAVEN_PACKAGING MAVEN_VERSION <<< ${MAVEN_ID}
  script:
    - >
      echo -e "groupId: ${MAVEN_GROUPID}\nartifactId: ${MAVEN_ARTIFACTID}\nversion: ${MAVEN_VERSION}\npackaging: ${MAVEN_PACKAGING}"
  • mvn help:evaluate -Dexpression=project.id -q -DforceStdout prints artifact identification information in the following format: com.group.id:artifactid:packaging:version
  • MAVEN_ID variable is parsed using IFS based on the colon (:) as a separator to get common maven variables like artifactId, groupId, version and packaging (explanation)
  • later these variables can be used in the code, for example for echoing values
  • IFS is a bash feature, thus corresponding GitLab runner should have bash installed

Upvotes: 0

Florian Huveteau
Florian Huveteau

Reputation: 31

Don't know if Gitlab can provide such a functionnality, but you might be able to retrieve this info using Maven help plugin :

version=$(mvn org.apache.maven.plugins:maven-help-plugin:3.1.1:evaluate -Dexpression=project.version -q -DforceStdout)

Upvotes: 3

Related Questions