Target

Using Jenkin:

  • Build a Spring Boot app to Jar file. Source code is on Github.
  • Upload Jar file to a GCP Compute engine and run.
  • In Jenkin job, can select the branch to deploy.

Prerequisites

  • Jenkin with plugins installed:
    • Office 365 Connector
    • Git
  • A compute engine in GCP
    • start-up script to install Java 8 and lsof
      apt-get update
      apt-get install openjdk-8-jdk lsof -y
      
  • A Spring Boot app with Gradle, pushed Github. I use my CORS demo app.

Let's go

Setup Compute engine

We need to config compute engine (VM) so that it can accept request at port 8080:

  • create a firewall rule that accept tcp 8080 with target tag spring
  • add target tag spring to the VM.
Create the Jenkin job
  • Add a parameter option to Office 365 Connector to choose the branch to deploy
  • Add git repo URL to Source Code Management, specify Branch as ${GIT_BRANCH} to select the value in Office 365 Connector parameter.
  • Build Jar file

    • In order to build a Jar file, add the following task to build.gradle
    bootJar {
        archiveFileName = "${archiveBaseName.get()}.${archiveExtension.get()}"
    }
    
    • As we open port 8080 in the VM, we need to specify the port we execute the Spring boot app, to do so, add the following to build.gradle file
    bootRun {
    systemProperties = System.properties
    }
    

    Now we can run the app manually by command

    java -Dserver.port=8080 -jar demo-cors.jar
    

    Let's Jenkin build the jar file by adding a Invoke Gradle Script step to Build:

  • Upload Jar file to VM
    The idea is to use scp to upload the Jar file to VM (a remote server). First we need to generate a pair of public, private key:
# login to jenkins user, if forgot the password use `sudo passwd jenkins` to change password
su - jenkins
ssh-keygen

Now a pair of key is generated at .ssh

ASRHQ614:~ jenkins$ ls .ssh/
id_rsa		id_rsa.pub	known_hosts

Add the public key content (id_rsa.pub) to VM by going to VM instance > Edit > SSH Keys

Test the connection:

su - jenkins
ssh <your-VM-ip>

Add a Execute Shell step to Build with following command:

scp -Cq -o StrictHostKeyChecking=no "build/libs/demo-cors.jar" "<your-VM-ip>:/home/jenkins/demo-cors.jar"
  • Execute the jar file

Add one more command to above Execute Shell step:

ssh jenkins@<your-VM-ip> -f 'kill -9 $(lsof -t -i:8080 -sTCP:LISTEN); java -Dserver.port=8080 -jar demo-cors.jar'

-f option : to run exit the ssh before running the commands
kill -9 $(lsof -t -i:8080 -sTCP:LISTEN): to kill the current app
java -Dserver.port=8080 -jar demo-cors.jar: execute the new jar file

Screenshot-2019-07-31-at-7.19.23-PM

Access <your-VP-ip>:8080 to see the result