Вы находитесь на странице: 1из 26

16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

Jenkins Pipeline to deploy Angular App to


AppEngine GCP
vijay kumar
Nov 20, 2018 · 10 min read

This post is all about creating a Continuous Deployment in Jenkins for Angular App to
GCP. This could also be used as a reference to deploy the Nodejs apps to GCP since most
of the stages are similar with language specific commands for building, packing and
deploying the app

Table of Contents
Table of Contents
A Brief Introduction:

Why GCP?

Install Jenkins

App and Repo Creation

Pipeline in Jenkins

* Click on the new item

* Create a sample pipeline project

* Describe the pipeline

* Pipeline script

CI in Jenkins

Jenkins Plugins

Configure Global Tools in Jenkins

Configure Credentials in Jenkins


https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 1/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

Configure Systems in Jenkins

Declarative Pipeline

Understanding Declarative Pipelines

Initial Declaration

Stages in Pipeline

Declaring Deploy stage

A Brief Introduction:

J enkins is one of the most widely used tools to develop Continuous Integration and
Continuous Delivery pipelines. The need for CI/CD cannot be overstated, since
the advent of developing agile based applications. That doesn’t mean that it should not
be used for the more traditional waterfall model though.

Continuous Integration is for continually triggering the phases such as


build/report/publish/package after every code commit and package the code ready for
deployment. This is mandatory since every time when a piece of code is checked in
your repo , say bitbucket, every time a build should be triggered and the app should be
bundled.

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 2/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

For the QA team to test the applications, they should be available in the sandbox at all
times. It is really inefficient to manually deploy the applications to the sandbox/ test
environments every time when a patch is made or a bug fix is done.

Enter Jenkins!!!. The world of CICD has been made simple with the introduction of
pipeline items, where different phases can be automated to happen after each
successful completion of a stage (Build/Package/Publish/Deploy)

Why GCP?
Micro-services architecture emphasises that each independent modules be hosted
as an independent application. GCP supports the micro-services architecture by
default where we can have a single project embed multiple applications (which are
language agnostic).

The AppEngine part of GCP supports automatic scaling based on the request
throughput and usage

Kubernetes is supported natively in GCP

GCP also makes a developers life much easier by allowing the admin to . SSH into
the remote machine and deploy manually.

There are many more advantages like debugging, logging which are supported natively
as well as support for greater set of analytic tools

Install Jenkins
The article in the link explains about installing and using Jenkins in a macOSX
machine. In a windows or Unix/Linux based machines use the respective package
managers to fetch the app. Please follow this link to either startup Jenkins as a
standalone or behind a NGINX reverse proxy

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 3/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

App and Repo Creation


I am not going to give an introduction on creating the angular/nodesjs/springboot
apps and push the code to a remote repo as it is beyond the scope of the article. There
are numerous online articles for that . Here are some of the references

Angular App reference:

A Quick Guide to Help you Understand and


Create Angular 6 Apps
This post is divided into two parts:
medium.freecodecamp.org

Nodejs App reference

Building a simple REST API with NodeJS and


Express.
Have you been working on front-end technologies
and been feeling like you’re missing out somethi…

medium.com

BItbucket references

Learn Git with Bitbucket Cloud | Atlassian Git Tutorial


Learn Git with Bitbucket Cloud

| Atlassian Git Tutorial Learn Git with Bitbucket Cloudwww.atlassian.com

Pipeline in Jenkins
Let us create a sample pipeline project in Jenkins

* Click on the new item

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 4/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

* Create a sample pipeline project

* Describe the pipeline

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 5/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

Con guring the ‘Discard old builds’ is optional

* Pipeline script

Now this is where scripting comes into picture. The user can select the Definition of the
pipeline to either be a Pipeline script or a Pipeline file that is stored in SCM

Snippet Generator

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 6/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

Here we are going to look at Pipeline declarations that are and executed directly from
SCM. This eliminates the need for maintaining a separate space in Jenkins for the
configuration file. The declaration pipeline is also much easier to configure.

CI in Jenkins
Continuous Integration is made possible in Jenkins by means of enabling Web-hooks.

Allow the webhooks plugin for the bitbucket server to be installed in your bitbucket
tool and then go to the repository settings

Now go to the Hooks section and enable the Bitbucket Server Webhooks to
Jenkins

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 7/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

Once the webhook is enabled , it gets reflected in the repo

Webhooks are nothing but functions that run on the web when something is triggered. In
our case, we would want the Jenkins pipeline function to be triggered when we push the
code to SCM, each time.

Now go back to Jenkins and enable the Build Trigger

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 8/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

Jenkins Plugins
There will be cases when some of the options in Jenkins may not be available by
default. So proper plugins need to be installed for every function.

For example if build is to be triggered on every push to bitbucket, then Bitbucket plugin
should be installed first. Here is a gist of all the plugins that I happen to install. Some of the
plugins may not be needed for your configuration.

Go to Manage Jenkins-> Manage plugins

Go to Available -> Search the plugins needed and install them. Make sure you select
Install without restart every time you wanted a plugin to be installed

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 9/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

Here is a gist of all plugins that I installed

1 All changes plugin


2
3 Ant
4
5 Apache HttpComponents Client 4.x API Plugin
6
7 Archived Artifact Url Viewer Plug-In
8
9 Artifact Deployer Plug-in
10
11
12 Artifact diff Plugin
13
14 Artifactory Plugin
15
16 Async Http Client
17
18 Authentication Tokens API Plugin
19
20 Bitbucket Approve Plugin
21
22 Bitbucket Branch Source
23
24 Bitbucket Plugin
25
26 bouncycastle API Plugin
27
28 Branch API
29
30 Build Pipeline Plugin
31
32 Build Timeout
33
34 Build-Publisher plugin
35
https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 10/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP
35
36 CloudBees Credentials Plugin
37
38 Credentials Binding
39
40 Credentials Plugin
41
42 Dashboard View
43
44 Delivery Pipeline Plugin
45
46 Deploy to container Plugin
47
48 Email Extension Plugin
49
50 Folders Plugin
51
52 Generic Webhook Trigger
53
54 Git client plugin
55
56 Git Parameter Plug-In
57
58 Git Pipeline for Blue Ocean
59
60 Git plugin
61
62 GIT server Plugin
63
64 GitHub API Plugin
65
66 GitHub Authentication plugin
67
68 GitHub Branch Source Plugin
69
70 GitHub Integration Plugin
71
72 GitHub plugin
73
74 Google OAuth Credentials plugin
75
76 HTML Publisher plugin
77
78 JDK Tool Plugin
79
80 JUnit Plugin
81
82 JWT for Blue Ocean
https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 11/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

83
84 Matrix Authorization Strategy Plugin
85
86 Matrix Project Plugin
87
88 Maven Integration plugin
89
90 Mercurial plugin
91
92 Multiple SCMs plugin
93
94 NodeJS Plugin
95
96 OAuth Credentials plugin
97
98 OpenShift Pipeline Jenkins Plugin
99
100 OpenShift Sync
101
102 OWASP Dependency-Check Plugin
103
104 OWASP Dependency-Track
105
106
107 OWASP Markup Formatter Plugin
108
109 Pipeline
110
111 Pipeline SCM API for Blue Ocean
112
113 Pipeline Utility Steps
114
115 Pipeline: API
116
117 Pipeline: Basic Steps
118
119 Pipeline: Build Step
120
121 Pipeline: Declarative
122
123 Pipeline: Declarative Agent API
124
125 Pipeline: Declarative Extension Points API
126
127 Pipeline: GitHub Groovy Libraries
128
129 Pipeline: Groovy
130
https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 12/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP
130
131
132 Pipeline: Input Step
133
134 Pipeline: Job
135
136 Pipeline: Milestone Step
137
138 Pipeline: Model API
139
140 Pipeline: Multibranch
141
142 Pipeline: Multibranch with defaults
143
144 Pipeline: Nodes and Processes
145
146 Pipeline: REST API Plugin
147
148 Pipeline: SCM Step
149
150 Pipeline: Shared Groovy Libraries
151
152 Pipeline: Stage Step
153
154 Pipeline: Stage Tags Metadata
155
156 Pipeline: Stage View Plugin
157
158 Pipeline: Step API
159
160 Pipeline: Supporting APIs
161
162 Plain Credentials Plugin
163
164 Publish Over SSH
165
166 Publish to Bitbucket Plugin
167
168 Script Security
169
170 Timestamper
171
172 Token Macro Plugin
173
174 Variant Plugin
175

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 13/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

Configure Global Tools in Jenkins


These are the building blocks of the pipeline allowing the user to execute build/publish
and deploy commands. We are going to make use of three major tools — Java, Git &
Node. Since Jenkins runs from local, it is important that the local machine has the
necessary tools installed in it. The other option is that we can instruct Jenkins to
download the tools over the internet.

Go to Manage Jenkins -> Global Tool Configuration

All the three tool con gurations are give here

Configure the executable paths of the tools by locating the bin folder for each

which java

which node

which git

Configure Credentials in Jenkins


Go to Jenkins -> Credentials

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 14/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

Select domain global -> Add credentials

Select Secret file option and upload the service account key generated from GCP

Make sure the Credentials and the Plain Credentials plugin are installed

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 15/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

Configure Systems in Jenkins


The next step would be to configure the systems such as the slack channels that Jenkins
interacts with, Also specify the Artifactory where the bundled apps will be published to,
most preferably your Jfrog artifactory

Go to Manage Jenkins-> Configure System

Make sure that the Artifactory plugin is installed

Declarative Pipeline

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 16/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

ipelines are nothing but a stream of different stages that we want the Jenkins to create.

P
These are provided as Jenkins interpretable configurations directives to create
the projects . Jenkins needs to know what commands are to be executed at a
certain stage. Since Jenkins is built using java, its compliers are integrated to
interpret ‘Groovy’ — its close ally. Groovy has a lot of embedded features of java along
with in-built closures. It is a statically typed, dynamic language which makes coding
much more easier. Thus the support for Groovy scripts by default

But many found that learning a whole new language for configuration was not
worthwhile and Jenkins came up with the solution — Declarative Jenkins Pipeline

I personally find declarative pipelines more appealing because of its ability to allow the
user to write the configuration as directives

Understanding Declarative Pipelines


Initial Declaration

A dvantage of using declarative pipelines is the ability to store the Jenkins


configuration over in SCM

The first statement starts with defining the directive for pipeline. All our directives
should be inside the pipeline block

pipeline{

agent any
}

Specifying the agent as any allows the Jenkins master to select any slave node under its
command to execute the pipeline script

Now the next step is specifying the tools to be used in Jenkins. Tools are nothing but
the build tools that are installed in the Jenkins instance. Before using the tools, we
should configure them as shown above

pipeline {
agent any

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 17/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

environment {
GOOGLE_PROJECT_ID = 'test-prj-cmd';

GOOGLE_SERVICE_ACCOUNT_KEY =
credentials('service_account_key');
}

tools {

git 'localGit'
jdk 'localJava'
nodejs 'localNode'

The environment variables to be used in Jenkins can be declared inside the


environment section like above. The usage of credentials directive is only possible if
the Credentials/Plain Credentials plugin have been installed. The Declaration pipeline
requires the instances of that particular class available in the environment. Now to use
the service account key that was uploaded in the Credentials page, we declare an
environment variable like above

The tools to be used can be declared specifying the named aliases of the executable
paths (see the Global tool section)

Stages in Pipeline
All pipelines involve multiple stages and declarative pipelines allow us to use stage
convention.

pipeline {
agent any

environment {
GOOGLE_PROJECT_ID = 'test-prj-cmd';
GOOGLE_SERVICE_ACCOUNT_KEY =
credentials('service_account_key');
}

tools {

git 'localGit'
jdk 'localJava'
nodejs 'localNode'

}
stages{
stage('Init'){
https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 18/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

steps{
sh '''#!/bin/bash
echo "JAVA_HOME = ${JAVA_HOME}";
echo "PATH = ${PATH}";
echo "MAVEN_HOME = ${M2_HOME}";

echo "this is the project id environment"+GOOGLE_PROJECT_ID;


npm install -g @angular/cli@6.0.8;
npm install
'''

echo "THis is the credentails:${GOOGLE_SERVICE_ACCOUNT_KEY}";


//readFileStep();
println "Init success..";

stage('Build'){
steps{

echo "Starting build ...."


sh '''#!/bin/bash
ng build --aot --prod
'''
println "BUILD NUMBER = $BUILD_NUMBER"
println "Build Success.."
}
post {
always {

-----------Post build steps ------

}
}
}

There is a lot of info here. I’ll try to explain the necessary directives.

S tages are the provisions to provide every phase that Jenkins has to go through.
We have the ability to provide multiple stages through stage declarative.

If a script needs to be executed then those can be provided inside the steps scope. We
are trying to interpret the script as bash command instead of the normal shell script (it

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 19/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

can also be done in bat mode for windows) and hence we declare the interpret to be
used as

#!/bin/bash

The post declarative provides provision for the user to specify any actions to be taken
after each successive phase.

println is a groovy command to print statements and echo is the command to print
statements in the console inside a script block

Declaring Deploy stage

1 pipeline {
2 agent any
3
4 environment {
5 GOOGLE_PROJECT_ID = 'test-prj-cmd';
6
7 GOOGLE_SERVICE_ACCOUNT_KEY = credentials('service_account_key');
8 }
9
10 tools {
11
12 git 'localGit'
13 jdk 'localJava'
14 nodejs 'localNode'
15
16 }
17 stages{
18 stage('Init'){
19 steps{
20 sh '''#!/bin/bash
21 echo "JAVA_HOME = ${JAVA_HOME}";
22 echo "PATH = ${PATH}";
23 echo "MAVEN_HOME = ${M2_HOME}";
24 echo env;
25 echo "this is the project id environment"+GOOGLE_PROJE
26 npm install -g @angular/cli@6.0.8;
27 npm install
28 '''
29
30
https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 20/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

31 echo "This is the credentails:${GOOGLE_SERVICE_ACCOUNT_KEY}"


32 println "Init success..";
33
34
35 }
36
37
38 }
39
40 stage('Build'){
41 steps{
42
43 echo "Starting build ...."
44 sh '''
45 #!/bin/bash
46 ng build --aot --prod
47 '''
48 println "BUILD NUMBER = $BUILD_NUMBER"
49 println "Build Success.."
50 }
51 post {
52 always {
53
54 notifyThroughEmail('Build-stage');
55
56 }
57
58 }
59
60 }
61 stage('Package'){
62 steps{
63 println "Starting package of war file..."
64 sh '''
65 #!/bin/bash
66 ng build --aot --prod
67 '''
68 println "$JENKINS_HOME $JENKINS_URL $BUILD_URL"
69 println "Packaging Success.."
70 }
71 post{
72 always{
73 notifyThroughEmail('Package-stage');
74
75 }
76 }
77 }
78 stage('Publish'){
https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 21/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP
78 stage( Publish ){
79 steps{
80 println('Starting publish..');
81 script{
82 def server = Artifactory.server('adtech-service-artifa
83 println("here is the server: "+server);
84 println("here is the server: ${server}");
85
86 def buildInfo = Artifactory.newBuildInfo();
87 buildInfo.env.capture = true;
88 //You can get the value of an environment variable col
89
90 //value = buildInfo.env.vars['env-var-name']
91
92 /*
93 To promote a build between repositories in Artifactory
94
95 def promotionConfig = [
96 // Mandatory parameters
97 'buildName' : buildInfo.name,
98 'buildNumber' : buildInfo.number,
99 'targetRepo' : 'libs-prod-ready-local',
100
101 // Optional parameters
102 'comment' : 'this is the promotion comm
103 'sourceRepo' : 'libs-staging-local',
104 'status' : 'Released',
105 'includeDependencies': true,
106 'copy' : true,
107 // 'failFast' is true by default.
108 // Set it to false, if you don't want the promotio
109 'failFast' : true
110 ]
111
112 // Promote build
113 server.promote promotionConfig */
114
115
116
117 buildInfo.retention maxBuilds: 10;
118 buildInfo.retention maxDays: 10;
119
120 println('Before adding upload spec');
121 def uploadSpec = """{
122 "files": [
123 {
124 "pattern": "*.
125 "target": "lib
https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 22/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

126 "recursive": "


127 "flat": "false
128 "props": "Vers
129 },
130 {
131 "pattern": "*.
132 "target": "lib
133 "recursive": "
134 "flat": "false
135 "props": "Vers
136 }
137 ]
138 }
139 """;
140 println('Before calling upload service');
141 server.upload(uploadSpec);
142
143
144 //download the uploaded artifact - this is to downloa
145 // the artifcatory if any
146 println('Before adding download spec');
147 def downloadSpec = """{
148 "files": [
149 {
150 "pattern": "**
151 "target": "lib
152 }
153 ]
154 }
155 """;
156 server.download(downloadSpec);
157
158
159 }
160 println('Publish Success');
161
162
163 }
164 post {
165 always {
166 notifyThroughEmail('Publish-stage');
167
168 }
169 }
170 }
171 stage('Deploy'){
172 steps{
173
https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 23/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP
173
174 //Deploy to GCP
175 sh """
176 #!/bin/bash
177 echo "deploy stage";
178 curl -o /tmp/google-cloud-sdk.tar.gz https://dl.google
179 tar -xvf /tmp/google-cloud-sdk.tar.gz -C /tmp/;
180 /tmp/google-cloud-sdk/install.sh -q;
181
182 source /tmp/google-cloud-sdk/path.bash.inc;
183
184
185 gcloud config set project ${GOOGLE_PROJECT_ID};
186 gcloud components install app-engine-java;
187 gcloud components install app-engine-python;
188 gcloud auth activate-service-account --key-file ${GOO
189
190 gcloud config list;
191 gcloud app deploy --version=v01;
192 echo "Deployed to GCP"
193 """
194 }
195 post{
196 always{
197 println "Result : ${currentBuild.result}";
198
199 notifyThroughEmail('Deploy-stage');
200
201 }
202 }
203 }
204 }
205
206 }
207
208
209 def notifyThroughEmail(String stage= "Default stage"){
210
211 emailext (
212 body:"""
213 Adtech-Service - Build # $BUILD_NUMBER - $currentBui
214
215
216 Check console output at $BUILD_URL to view the resul
217 """,

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 24/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

The above gist gives a detail description of how to deploy an Angular app to the GCP
App Engine. Again the presence of app.yaml is required and the article assumes it to be
present implicitly. We require gcloud sdk to interact and most of its components to
interact with GCP

Use curl to get the gcloud sdk. Specify the required version to be fetched

Unzip it using the tar command to /tmp/folder

Now install gcloud sdk in jenkins by from installation script

Set the Path variable for cloud specifying where to find the bin location

Configure the project to be used using the following command

gcloud config set project <project_id>

Authenticate into the GCP using the following command

gcloud auth activate-service-account --key-file <the account json


file, in this case the credentials provided in environment>

Now use the gcloud command to deploy

gcloud app deploy

Note: App.yaml contains the configuration for deploying the app in GCP

There are other parts I have added where in the user can publish the artifactory and also
send email notifications of every stage but chose not to explain them since the article’s
main focus is to deploy to google cloud

Now come back to Jenkins and either trigger a build manually using — Build Now or
by checking in some changes to SCM. You should see all the stages of the pipeline
successfully executed

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 25/26
16/01/2020 Jenkins Pipeline to deploy Angular App to AppEngine GCP

Each stage with the build result

I hope this gives a good idea to get started with Jenkins. Shoot me up with any
questions and I will try to answer them as best as possible. Happy reading!!!

Jenkins Gcp Nodejs

About Help Legal

https://medium.com/@sportans300/jenkins-pipeline-to-deploy-angular-app-to-appengine-gcp-1f58160e2779 26/26

Вам также может понравиться