Writing a Declarative Jenkinsfile for Angular Applications

BLOG
X
min read

In the previous article, we discussed the details of a declarative Jenkins pipeline built for a java application. now that we know what CI/CD is and how can we use Jenkins to achieve our automation goals. In this article, we will discuss how can we apply the same concepts for an angular application to automate its build, test and deployment tasks.

Jenkins file break down

The Jenkins file that we’re going to write is very similar to the one we wrote before. Let’s highlight the differences.

Tools

we’re going to use NodeJS to be able to make Jenkins perform tasks like building the angular app. (Make sure that NodeJS plugin is installed for Jenkins. This plugin can be installed from this link https://plugins.jenkins.io/nodejs/ )

tools { nodejs "NodeJS" }


Stages

In our pipeline, we’re going to perform the following tasks (build the app, test the app, containerize it, and finally deploy it to K8S) so let’s see part of the file associated with each step.

Build and Test stage

This stage is very simple and straight forward. We Will use NPM (bundled with NodeJs module that we installed earlier) to perform both build and test on our app We can rely on a custom-defined parameter to decide whether we’re going to skip the tests or not. the associated Jenkins file stage should look like this.

 stage('Build') {
        steps {
           script{
             if(params.SKIP_TESTS){
               sh 'npm install'
               sh 'npm run build:${ENV}'
             }else{
               sh 'npm install'
               sh 'npm run test'
               sh 'npm run build:${ENV}'
                    }
                  }
               }
             }

SonarQube stage

Code coverage is one important metric that can help you understand how much of your code is covered in tests. It is one of the metrics that should be taken into consideration when assessing your overall code quality.

There are a simple set of steps required to integrate the tests you have written in your Jenkins job. In this example, we are using a decelerative pipeline with a Jenkins file in the root directory of our angular application.

1. Your tests can run in a UIless browser. modify your karma.conf.js file and add the following lines to make it run in a UIless mode

customLaunchers: {

    ChromeHeadless: {

        base: 'Chrome',

        flags: [

           '--headless',

           '--disable-gpu',

           '--no-sandbox',

           '--remote-debugging-port=9222',

         ]

      }

},

browsers: ['ChromeHeadless'],

singleRun: true,

restartOnFileChange: true


2. In your package.json file, configure the following task

"test": "ng test --watch=false --code-coverage"


3. In your Jenkins file, in the build step invoke this task.

Integrating SonarQube with Jenkins pipeline

Wouldn’t it be great if you can assess your angular project quality at any point in time? Especially if you are applying micro frontend architecture in your project. it will be very tedious and time-consuming to generate a code coverage report. You will have to go through all your micro frontends and run the code coverage command then gather all the output reports in one report manually to hand it to the architect or the team lead.

That is when SonarQube comes into play. Sonar enables you to monitor and assess your project’s quality easily with a simple and user-friendly interface.

The proposed solution here is to integrate your Jenkins pipeline with sonar so whenever you trigger a deployment, a code coverage report and test execution report should be generated and given to sonar. Sonar then displays these reports in a user-friendly manner along with static code analysis details.

We will assume that you already have SonarQube Installed. And here are the solution steps

Solution steps

1. Connect your Jenkins with SonarQube. This is done by going to ‘Manage Jenkins -> Configure System -> SonarQube Server’ then add the details of your SonarQube server


2. To run project analysis with Jenkins a scanner plugin must be installed. This is done by going to ‘Manage Jenkins -> Global Tool Configuration -> SonarQube Scanner ’


3. Next step is to install two plugins in our angular application that will generate the test coverage report and the test execution report. This is done by executing the following commands

npm install karma-coverage-istanbul-reporter

npm install karma-sonarqube-unit-reporter


4. The second step is to configure these plugins to generate the reports we want. This is done by adding these changes to your karma.

plugins: [

require ( karma-coverage-istanbul-reporter"),

require ( korma-sonarqube-unit-reporter')

],

coveragelstanbul Reporter: {

dir: require( 'path').join(_dirname, 'coverage),

reports: [ 'lcovonly').

fixWebpackSourcePaths: true

},

reporters: [ 'sonarqubeUnit' ],

sonarQubeUnitReporter: {

     sonarQubeVersion: 'LATEST',

     outputfile: 'test-reports/ut_repor.xml',

     overrideTestDescription: true,

     testPaths: [./src'],

     testFilePattern: .spec.ts',

     useBrowserName: false

},


5. The final step is to configure our Jenkins Job using the declarative pipeline file to use the generated reports and provide some information for SonarQube regarding where the tests files are, what to scan and what not to scan, etc. and this is done by adding a sonar stage in our pipeline like the following

stage ( 'SonarQube analysis') {
    environment {

        scannerhome= tool 'SonarQubeScanner'

   }

   steps {

      withSonarQubeEnv( 'SonarQube) {
          sh ' '' '
          ${scannerHome/bin/sonar-scanner\
          -D sonar .projectKey-creation-bo-ui \
          -D sonar .projectName-creation-bo-ui \
          -D sonar.sources= src \
          -D sonar.tests= src\
          -D sonar.typescript.tsconfigPath=tsconfig.json \
          -D sonar.exclusions-node_modules/** \ 
          -D sonar.test. inclusions= **/* .spec.ts \
          -D sonar, testExecut lonReportPaths-test-reports/ut_report.xml\
           -D sonar.javascript.lcov.reportPaths-coverage/lcov.info
           ' ' '

         }

    }

 }


Let us explain the above stage in detail.

The first thing we are doing here is defining the location of our scanner that we installed in step 2. You only need to provide the scanner name.

In the steps, we are pointing here at SonarQube server that we configured in step 1.

Then we‘re passing some information to sonar server. About our files locations and where our tests are and where can sonar find the execution report and the coverage report.

Docker stage

After we are done with building and testing our app. Time to create a docker image which we can then deploy onto Kubernetes dynamically using the docker registry and Kubernetes namespaces declared in the parameters.

stage('Docker') {
   stages {
      stage('Create Image') {
         steps {
             script {
                 sh 'sed -i "s|@DOCKER_REGISTRY@|${DOCKER_REGISTRY}|g" Dockerfile'
                 dockerImage = docker.build registry + "offices-reports-ui:$BUILD_NUMBER"
             }
          }
       }
       stage('Push Image') {
          steps {
             script {
                 docker.withRegistry('') {
                     dockerImage.push()
                     }
              }
          }
        }
     }
  }


K8s Deploy

The final stage is to deploy the generated docker image into k8s cluster using the below commands.

stage('K8s deploy') {
    steps {
        sh """
sed -i "s|@BUILD_NUMBER@|${BUILD_NUMBER}|g" $WORKSPACE/kubernetes.yml
sed -i "s|@HOST@|${HOST}|g" $WORKSPACE/kubernetes.yml
sed -i "s|@DOCKER_REGISTRY@|${DOCKER_REGISTRY}|g" $WORKSPACE/kubernetes.yml
sed -i "s|@NAMESPACE@|${NAMESPACE}|g" $WORKSPACE/kubernetes.yml
kubectl apply -f $WORKSPACE/kubernetes.yml -n ${NAMESPACE} --kubeconfig /var/jenkins_home/k8s/${NAMESPACE}
"""
     }
   }

Modernizing Legacy Apps​

Maecenas mollis sagittis ante, eleifend ultricies sapien. Nam ultricies risus et augue auctor vulputate gravida eget sem. Quisque mollis gravida magna, eu semper eros pharetra in. Sed et elit sit amet odio rutrum consectetur vel vel ante. Praesent vitae elementum lacus. Vivamus efficitur nunc tortor, cursus lobortis purus placerat ut. Maecenas ut aliquet ante, vel finibus lorem. Nulla facilisi. Donec maximus elementum pulvinar.

test heading

h1 text

h3

Impact

Sample article featured image
Pellentesque posuere sem in ipsum venenatis, at bibendum lorem aliquam. Nullam condimentum tempus orci nec commodo. Maecenas malesuada elementum metus, non aliquam est elementum sed. Integer ac finibus ligula, id venenatis lectus. Mauris non eleifend enim. Pellentesque eu congue justo. In ornare dapibus nisi, sit amet feugiat neque. Vivamus mollis, lectus quis gravida viverra, risus ligula congue felis, ut laoreet sem nisi in tortor. Sed vel ligula nulla.
“Quisque mollis purus nec pulvinar rutrum. Duis faucibus sed orci vel pellentesque. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec non volutpat eros, nec placerat mi. Praesent porta felis ut urna sagittis, sit amet placerat nisl porttitor.”

Nunc tempor molestie velit id dictum. Aenean ac venenatis ipsum, sit amet sodales tortor. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque posuere sem in ipsum venenatis, at bibendum lorem aliquam.

Nullam condimentum tempus orci nec commodo. Maecenas malesuada elementum metus, non aliquam est elementum sed. Integer ac finibus ligula, id venenatis lectus. Mauris non eleifend enim. Pellentesque eu congue justo. In ornare dapibus nisi, sit amet feugiat neque. Vivamus mollis, lectus quis gravida viverra, risus ligula congue felis, ut laoreet sem nisi in tortor. Sed vel ligula nulla.

data-acc-source-start

Ensure that Modernizing your Legacy Application is the Right Decision

Our expert consultants work closely with you to understand you organization's business drivers, then conduct an in-depth business goals and that every dollar invested is directed towards the right solution

Depend on a Tailored, Phased Application Modernization Strategy

Our expert consultants work closely with you to understand you organization's business drivers, then conduct an in-depth business goals and that every dollar invested is directed towards the right solution

Streamline the Transition from Old to New

Our expert consultants work closely with you to understand you organization's business drivers, then conduct an in-depth business goals and that every dollar invested is directed towards the right solution

data-acc-source-end

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur elementum, elit a pellentesque placerat, nisl quam blandit orci, at maximus eros nunc nec lacus. Nullam euismod consequat libero, eget suscipit ligula lacinia nec. Nunc finibus dapibus quam, eu convallis magna. Nulla finibus ut risus in sodales. Cras tristique nisi non mattis volutpat. Nullam venenatis varius nisl, dictum ornare lorem dictum rhoncus. Nulla sem nunc, lobortis et massa sed, ultrices convallis justo. Quisque laoreet nibh sit amet arcu rhoncus accumsan. Proin at elementum lacus, at maximus mi. Curabitur vulputate urna mollis lacinia auctor. Donec venenatis finibus magna id tempor. Duis at mattis odio. Aenean eu tempus justo. Donec est arcu, vulputate quis risus et, pharetra imperdiet velit.

Vivamus ut dignissim quam.

No items found.
Article carousel image 1
Article carousel image 2
Article carousel image 3
Author
Yomna Anwar
Posted on
15 Aug 2021
We’re your partner in addressing

real human needs.

Align IT Initiatives with Strategic Business Goals
Plus sign iconMinus sign icon
10X
Increase in transactions
per second

Heading 1

Heading 2

Heading 3

Heading 4

Heading 5
Heading 6

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

Block quote

Ordered list

  1. Item 1
  2. Item 2
  3. Item 3

Unordered list

  • Item A
  • Item B
  • Item C

Text link

Bold text

Emphasis

Superscript

Subscript

Modernizing Legacy Apps​

Maecenas mollis sagittis ante, eleifend ultricies sapien. Nam ultricies risus et augue auctor vulputate gravida eget sem. Quisque mollis gravida magna, eu semper eros pharetra in. Sed et elit sit amet odio rutrum consectetur vel vel ante. Praesent vitae elementum lacus. Vivamus efficitur nunc tortor, cursus lobortis purus placerat ut. Maecenas ut aliquet ante, vel finibus lorem. Nulla facilisi. Donec maximus elementum pulvinar.

Impact

Sample article featured image
Pellentesque posuere sem in ipsum venenatis, at bibendum lorem aliquam. Nullam condimentum tempus orci nec commodo. Maecenas malesuada elementum metus, non aliquam est elementum sed. Integer ac finibus ligula, id venenatis lectus. Mauris non eleifend enim. Pellentesque eu congue justo. In ornare dapibus nisi, sit amet feugiat neque. Vivamus mollis, lectus quis gravida viverra, risus ligula congue felis, ut laoreet sem nisi in tortor. Sed vel ligula nulla.
“Quisque mollis purus nec pulvinar rutrum. Duis faucibus sed orci vel pellentesque. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec non volutpat eros, nec placerat mi. Praesent porta felis ut urna sagittis, sit amet placerat nisl porttitor.”

Nunc tempor molestie velit id dictum. Aenean ac venenatis ipsum, sit amet sodales tortor. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque posuere sem in ipsum venenatis, at bibendum lorem aliquam.

Nullam condimentum tempus orci nec commodo. Maecenas malesuada elementum metus, non aliquam est elementum sed. Integer ac finibus ligula, id venenatis lectus. Mauris non eleifend enim. Pellentesque eu congue justo. In ornare dapibus nisi, sit amet feugiat neque. Vivamus mollis, lectus quis gravida viverra, risus ligula congue felis, ut laoreet sem nisi in tortor. Sed vel ligula nulla.

data-acc-source-start

Ensure that Modernizing your Legacy Application is the Right Decision

Our expert consultants work closely with you to understand you organization's business drivers, then conduct an in-depth business goals and that every dollar invested is directed towards the right solution

Depend on a Tailored, Phased Application Modernization Strategy

Our expert consultants work closely with you to understand you organization's business drivers, then conduct an in-depth business goals and that every dollar invested is directed towards the right solution

Streamline the Transition from Old to New

Our expert consultants work closely with you to understand you organization's business drivers, then conduct an in-depth business goals and that every dollar invested is directed towards the right solution

data-acc-source-end

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur elementum, elit a pellentesque placerat, nisl quam blandit orci, at maximus eros nunc nec lacus. Nullam euismod consequat libero, eget suscipit ligula lacinia nec. Nunc finibus dapibus quam, eu convallis magna. Nulla finibus ut risus in sodales. Cras tristique nisi non mattis volutpat. Nullam venenatis varius nisl, dictum ornare lorem dictum rhoncus. Nulla sem nunc, lobortis et massa sed, ultrices convallis justo. Quisque laoreet nibh sit amet arcu rhoncus accumsan. Proin at elementum lacus, at maximus mi. Curabitur vulputate urna mollis lacinia auctor. Donec venenatis finibus magna id tempor. Duis at mattis odio. Aenean eu tempus justo. Donec est arcu, vulputate quis risus et, pharetra imperdiet velit.

Vivamus ut dignissim quam.

No items found.
Article carousel image 1
Article carousel image 2
Article carousel image 3
Author
This is some text inside of a div block.
Posted on
This is some text inside of a div block.
Topics