How to retrieve data from pom.xml file to .gitlab-ci.ylm file?

Problem to solve

I’m creating a CI/CD pipeline using gitlab. The project requirement is there is a pom.xml file and I need to retrieve project name and Ip address from pom.xml file and pass it into .gitlab-ci.yml file. below are the format :

Pom.xml file

  1. this is the pom.xml file. i need to capture below ponts
    1. all the staging profile id’s.
    2. then I need to capture ‘docker-repository’ Ip address only. without port
    3. then Project

.gitlab-ci.yml file

  1. Then I need to pass above captured data to below gitlab-ci.yml file

build_and_release:
extends: .build_and_release_template
variables:
PROJECT_NAME: “Project name”
SERVER_IP: “190.167.17.02”

This ought to work:

build_and_release:
  extends: .build_and_release_template
  variables:
    POM_XML_FILE: pom.xml
  before_script:
    - export PROJECT_NAME=$(grep -oP '<Project>\K[^<]+' "$POM_XML_FILE")
    - export SERVER_IP=$(grep -oP '<docker-repository>\K[^<]+' "$POM_XML_FILE")
  script:
    - [...]

Thank you for your reply.
Now I’m passing like below. But I have an another issue. PROJECT_NAME and SERVER_IP is passing correctly to ‘script’ level. but SERVER_IP is not passing to after_script level (PROJECT_NAME is passing). log shows as below. What could be the reason?

Log:
Running after script…

$ echo “Deploying to $SERVER_IP for project $PROJECT_NAME” # collapsed multi-line command
Deploying to for project TEST PROJECT

Script:

.build_and_release_template:
stage: build
image: docker:24.0.5-cli-alpine3.18
variables:
POM_XML_FILE: java/containers/pom.xml

before_script:
- export PROJECT_NAME=$(awk -F’[<>]’ ‘//{p=1} /._staging</id>/{id=$3} /.</obsasProject>/{if(p) print $3; exit}’ “$POM_XML_FILE”)
- export SERVER_IP=$(awk -F’[<>]’ ‘//{p=1} /._staging</id>/{id=$3} /.</docker-repository>/{if(p) {split($3, a, “:”); print a[1]; exit}}’ “$POM_XML_FILE”)

script:
- echo “Building and releasing $PROJECT_NAME to server at $SERVER_IP”

after_script:
- |
echo “Deploying to $SERVER_IP for project $PROJECT_NAME

This happens because, according to the GitLab after_script documentation:

Scripts you specify in after_script execute in a new shell, separate from any before_script or script commands. As a result, they:

  • Don’t have access to changes done by commands defined in the before_script or script, including:
    • Command aliases and variables exported in script scripts.

If you want to handle deployment as part of the after_script and not part of the script itself, you’ll need to set the $SERVER_IP and $PROJECT_NAME variables again:

after_script:
  - export PROJECT_NAME=$(awk -F’[<>]’ ‘//{p=1} /._staging</id>/{id=$3} /.</obsasProject>/{if(p) print $3; exit}’ “$POM_XML_FILE”)
  - export SERVER_IP=$(awk -F’[<>]’ ‘//{p=1} /._staging</id>/{id=$3} /.</docker-repository>/{if(p) {split($3, a, “:”); print a[1]; exit}}’ “$POM_XML_FILE”)
  - echo “Deploying to $SERVER_IP for project $PROJECT_NAME”
1 Like