Get Jenkins BUILD_NUMBER variable and display it in angular application

Viewed 5544

I deploy an angular application by Jenkins and I want to display the build number in the footer of the page. I know that while Jenkins is running the job, it sents a system environment variable BUILD_NUMBER. I read some articles but none is saying how can we get this variable from the OS?

1 Answers

Here is a workaround.

You can use pre and post build event to replace a version-tag in environment.prod.ts file.

export const environment = { production: true, system: 'prod', version: '%VERSION%' };

install npm-replace:

npm install replace --save-dev

package.json

"build:prod": "ng build --env=prod", 
"prebuild:prod": "replace '%VERSION%' $VERSION src/environments/environment.prod.ts", 
"postbuild:prod": "replace $VERSION '%VERSION%' src/environments/environment.prod.ts",

In jenkins run the following command

VERSION="$BUILD_NUMBER" npm run build:prod

Reference: Request: Method to pass environment variables during build vs file.

UPDATE

Another way to achieve mentioned behavior is to use sed utility which is pre-installed in Linux. You can follow these steps

  1. Update environment.prod.ts to have a pre-defined key. Let's suppose jenkinsBuildNO. e.g

    export const environment = { production: true, system: 'prod', version: 'jenkinsBuildNO' };

  2. Create another step in jenkins to update jenkinsBuildNO in environment.prod.ts with Build No. or something other.

    sed -i -e 's/jenkinsBuildNO/%BUILD_NUMBER%/g' src/environments/environment.prod.ts

  3. start angular build. ng buld --prod

  4. Update build no with our pre-defined key jenkinsBuildNO in environment.prod.ts

    sed -i -e 's/%BUILD_NUMBER%/jenkinsBuildNO/g' src/environments/environment.prod.ts

Related