donal
2018-05-09 ad843635bc84a278e58922811cab192102ebb931
commit | author | age
3772d9 1 # Attack of the Pipelines
0f4d08 2
867471 3 > In this exercise we will explore the sample TODO List application and create a pipeline in Jenkins to build and deploy our code.
3772d9 4
D 5 ![jenkins-time](../images/exercise2/jenkins-time.jpg)
6
78b569 7 ## Exercise Intro
D 8 This lesson is focused on creating a pipeline for our application. What is a pipeline? A pipeline is a series of steps or stages that takes our code from source to a deployed application. There can be many stages to a pipeline but a simple flow is to run a `build > bake > deploy`. Usually the first stage is trigger by something like a git commit. There could be many steps in each of these stages; such as compiling code, running tests and linting. All of these are done to try and drive up code quality and give more assurance that what is deployed is behaving as expected. In the exercise we will create Jenkins pipeline by configuring it through the UI, this will create an un-gated pathway to production
9
10 First we will explore the sample application and get it running locally. The sample app is a `todolist` app - the `Hello World` app of the modern day. 
11
12 #### Why create pipelines
13 * Assurance - drive up code quality and remove the need for dedicated deployment / release management teams
14 * Freedom - allow developers to take ownership of how and when code gets built and shipped
2059d3 15 * Reliability - pipelines are a bit boring; they execute the same way each and every time they're run!
78b569 16 * A pathway to production:
D 17     - Puts the product in the hands of the customer quicker
18     - Enables seamless and repeatable deploys
19     - More prod like infrastructure increases assurance
20     - “We have already done it” behavior de-risks go live
21
5a16fd 22 _____
0f4d08 23
D 24 ## Learning Outcomes
3772d9 25 As a learner by the end of this lesson you will be able to
D 26
27 - Build and run the full stack of the TODO List application locally
28 - Create an un-gated pipeline using the Jenkins UI for the backend and frontend
29 - Add branching to the pipeline to target specific namespace
0f4d08 30
D 31 ## Tools and Frameworks
8a47e6 32 > The following tools are used throughout this exercise. Familiarity with them is not required but knowing what they are may help. You will not need to install Vue or Mongodb they are taken care of by our `todolist` app.
0f4d08 33
D 34 1. [Jenkins](https://jenkins.io/) - OpenSource build automation server; highly customisable through plugins
3772d9 35 1. [NodeJS](https://nodejs.org/en/) - Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.
D 36 1. [MongoDB](https://www.mongodb.com/what-is-mongodb) - MongoDB stores data in flexible, JSON-like documents, meaning fields can vary from document to document and data structure can be changed over time
37 1. [VueJS](https://vuejs.org/) - Vue (pronounced /vjuː/, like view) is a progressive framework for building user interfaces. It is designed from the ground up to be incrementally adoptable, and can easily scale between a library and a framework depending on different use cases. It consists of an approachable core library that focuses on the view layer only, and an ecosystem of supporting libraries that helps you tackle complexity in large Single-Page Applications.
0f4d08 38
5a16fd 39 ## Big Picture
3772d9 40 > From the previous exercise; we created some supporting tooling needed by our app/
5a16fd 41
D 42 _____
0f4d08 43
D 44 ## 10,000 Ft View
3772d9 45 > _This lab requires users to take the sample TODO app and create a build pipeline in Jenkins by clicking your way to success ending up with an app deployed to each of the namespaces created previously_
5a16fd 46
3772d9 47 2. Import the projects into your gitlab instance. See README of each for build instructions
5a16fd 48
3772d9 49 2. Deploy a `MongoDB` using the provided template to all project namespace.
D 50
51 2. Create 2 pipline with three stages (`build`, `bake`, `deploy`) in jenkins for `develop` & `master` branches on the `todolist-fe` such that:
c3a934 52     * a `Build` job is responsible for compiling and packaging our code:
3772d9 53         1. Checkout from source code (`develop` for `<yourname>-dev` & `master` for `<yourname>-test`)
D 54         2. Install node dependencies and run a build / package
c3a934 55         3. Send the package to Nexus
D 56         4. Archive the workspace to persist the workspace in case of failure
57         4. Tag the GitLab repository with the `${JOB_NAME}.${BUILD_NUMBER}` from Jenkins. This is our `${BUILD_TAG}` which will be used on downstream jobs.
58         5. Trigger the `bake` job with the `${BUILD_TAG}` param
59     * a `Bake` job should take the package and put it in a Linux Container
3772d9 60         1. Take an input of the previous jobs `${BUILD_TAG}` ie `${JOB_NAME}.${BUILD_NUMBER}`.
D 61         2. Checkout the binary from Nexus and unzip it's contents
c3a934 62         3. Run an oc start-build of the App's BuildConfig and tag it's imagestream with the provided `${BUILD_TAG}`
3772d9 63         4. Trigger a deploy job using the parameter `${BUILD_TAG}`
c3a934 64     * a `deploy` job should roll out the changes by updating the image tag in the DC:
3772d9 65         1. Take an input of the `${BUILD_TAG}`
D 66         2. Patch / set the DeploymentConfig to the image's `${BUILD_TAG}`
67         3. Rollout the changes
68         4. Verify the deployment
69
70 2. Repeat the above setup for the backend `todolist-fe`. TIP - use the copy config to speed things up!
71
72 2. Verify that both apps and the DB are talking to one another as expected.
0f4d08 73
D 74 ## Step by Step Instructions
f2b1b4 75 > This is a fairly structured guide with references to exact filenames and sections of text to be added.
0f4d08 76
14268c 77 ### Part 1 - Explore the Todo List App
f2b1b4 78 > _In this part of the exercise we will explore the sample application, become familiar with it locally before building and deploying in OCP Land_
5a16fd 79
752f2a 80 #### 1a Todolist-fe
256ca9 81
f2b1b4 82 2. Git clone the `todolist-fe` project to somewhere sensible and checkout the `develop` branch.
D 83 ```bash
ad8436 84 git clone https://github.com/rht-labs/todolist-fe.git
D 85 cd todolist-fe
86 git checkout develop
256ca9 87 ```
ad8436 88 ```bash
D 89 ./git-pull-all.sh
0f4d08 90 ```
f2b1b4 91
486224 92 2. Open up Gitlab and login. Create a new project (internal) in GitLab called `todolist-fe` to host your clone of the project and copy it's remote address. ![new-gitlab-proj](../images/exercise2/new-gitlab-proj.png)
f2b1b4 93
D 94 2. In your local clone of the `todolist-fe`, remove the origin and add the GitLab origin by replacing `<YOUR_GIT_LAB_PROJECT>`. Push your app to GitLab
95 ```bash
ad8436 96 git remote set-url origin <YOUR_GIT_LAB_PROJECT>
486224 97 # verify the origin has been updated
ad8436 98 git remote -v
D 99 git push -u origin --all
0f4d08 100 ```
f2b1b4 101
D 102 2. To get the app running locally; first check you've got node and npm installed
103 ```bash
ad8436 104 node -v
D 105 npm -v
f2b1b4 106 ```
D 107 <p class="tip" > 
108 NOTE - If you are missing these dependencies; install them with ease using the [Node Version Manager](https://github.com/creationix/nvm)
109 </p>
110 ![node-version](../images/exercise2/node-version.png)
111
112 2. The `todolist-fe` has a package.json at the root of the project, this defines some configuration for the app including it's dependencies, dev dependencies, scripts and other configuration. Install the apps dependencies
113 ```bash
ad8436 114 npm install
f2b1b4 115 ```
D 116
514d1d 117 2. The `todolist-fe` has some scripts defined in the package.json at the root of the project. A snippet of the npm scripts are shown below. To run any of these scripts run `npm run <SCRIPT_NAME>`. Let's start by serving our application
f2b1b4 118  ![npm-scripts](../images/exercise2/npm-scripts.png)
D 119 ```bash
120 npm run serve
121 ```
122
486224 123 2. This will take sometime to execute; but once done it should open the browser for you displaying the homepage of the `todolist-fe` app.
f2b1b4 124  ![todo-list-app](../images/exercise2/todo-list-app.png)
486224 125     * Click 'Todo' at the top of the home page to get to the above page.
514d1d 126     * The server hosting it live reloads; so if you make changes to your code base the app will live update
f2b1b4 127     * The Data you see in the screen is dummy / stubbed data. This is served up when there is no backend connection found
D 128
514d1d 129 2. The app is a todolist manager built in Vue.js. Play around with the App. You will notice when you add todos they appear and clear as expected. If you refresh the page you'll lose all additions. This is because there is no persistence layer. We will add one in the next part.
f2b1b4 130
D 131 3. The structure of the `todolist-fe` is as follows.
132 ```bash
133 todolist-fe
134 ├── jest.config.js
135 ├── jsconfig.json
136 ├── nightwatch.config.js
137 ├── node_modules
138 ├── package.json
139 ├── public
140 │   ├── favicon.ico
141 │   ├── img
142 │   ├── index.html
143 │   └── manifest.json
144 ├── src
145 │   ├── App.vue
146 │   ├── assets
147 │   ├── components
486224 148 │   │   └── *
f2b1b4 149 │   ├── config
D 150 │   ├── main.js
151 │   ├── registerServiceWorker.js
152 │   ├── router.js
153 │   ├── scss
154 │   ├── services
155 │   ├── store
486224 156 │   │   └── *
f2b1b4 157 │   └── views
486224 158 │       └── *
f2b1b4 159 ├── tests
D 160 │   ├── e2e
161 │   └── unit
162 └── vue.config.js
163 ```
164 where the following are the important things:
165     * `./src` is the main collection of files needed by the app. The entrypoint is the `main.js` which is used to load the root `App.vue` file.
166     * `./node_modules` is where the dependencies are stored
867471 167     * `./test` contains our end-to-end tests and unit tests. More covered on these in later exercises.
486224 168     * `./src/components` contains small, lightweight reusable components for our app. For example, the `NewTodo` component which encapsulates the styling, logic and data for adding a new todo to our list
f2b1b4 169     * `./src/store` is the `vuex` files for managing application state and backend connectivity
D 170     * `./src/views` is the view containers; which are responsible for loading components and managing their interactions.
171     * the `./src/router.js` controls routing logic. In our case the app only has one real endpoint.
172     * `./src/scss` contains custom  SCSS used in the application.
173     * `./*.js` is mostly config files for running and managing the app and the tests
0f4d08 174
1937a3 175 2. To prepare Nexus to host the binaries created by the frontend and backend builds we need to run a prepare-nexus script. Before we do this we need to export some variables change `<YOUR_NAME>` and `somedomain` accordingly.
256ca9 176 ```bash
12ca4a 177 export NEXUS_SERVICE_HOST=$(oc get route nexus --template='{{.spec.host}}' -n <YOUR_NAME>-ci-cd)
256ca9 178 export NEXUS_SERVICE_PORT=80
A 179 npm run prepare-nexus
180 ```
181 <p class="tip">
182 NOTE - This step in a residency would be automated by a more complex nexus deployment in the ci-cd project
183 </p>
184
752f2a 185 #### 1b Todolist-api
f9e311 186
3691a1 187 2. Now let's move on to the `todolist-api` and wire them together. As with the `todolist-fe` we need to clone the repo and add it to our GitLab in the cluster.
D 188 ```bash
ad8436 189 git clone https://github.com/rht-labs/todolist-api.git
D 190 cd todolist-api
191 git checkout develop
256ca9 192 ```
ad8436 193 ```bash
D 194 ./git-pull-all.sh
3691a1 195 ```
D 196
514d1d 197 2. On GitLab; create a new project (internal) called `todolist-api` to host your clone of the project and copy it's remote address as you did for the previous repositories.
3691a1 198
D 199 2. In your local clone of the `todolist-api`, remove the origin and add the GitLab origin by replacing `<YOUR_GIT_LAB_PROJECT>`. Push your app to GitLab
200 ```bash
ad8436 201 git remote set-url origin <YOUR_GIT_LAB_PROJECT>
D 202 ```
203 ```bash
204 git push -u origin --all
3691a1 205 ```
D 206
207 2. Once pushed; explore the application. It is a NodeJS application with the Express.js framework and MongoDB for persistent storage. Same as before, the `package.json` defines most of the configuration etc. Install the dependencies
208 ```bash
486224 209 # npm i === npm install
ad8436 210 npm i
3691a1 211 ```
D 212
213 2. While the dependencies are being installed; explore the project structure.
214 ```bash
215 todolist-api
216 ├── Dockerfile
217 ├── Gruntfile.js
218 ├── README.md
219 ├── node_modules
220 ├── package-lock.json
221 ├── package.json
222 ├── server
223 │   ├── api
224 │   │   └── todo
225 │   ├── app.js
226 │   ├── components
227 │   │   └── errors
228 │   ├── config
229 │   │   ├── environment
230 │   │   ├── express.js
231 │   │   ├── local.env.sample.js
232 │   │   └── seed.js
233 │   ├── mocks
234 │   │   ├── mock-routes-config.json
235 │   │   ├── mock-routes.js
236 │   │   └── mock-routes.spec.js
237 │   ├── routes.js
238 │   └── views
239 │       └── 404.html
240 └── tasks
241     └── perf-test.js
242 ```
243 where the following are the important things:
244     * `./server` is the main collection of files needed by the app. The entrypoint is the `app.js`
245     * `./node_modules` is where the dependencies are stored
246     * `./server/api` is where the api's controller, data model & unit test are stored. 
247     * `./server/mocks` is a mock server used for when there is no DB access    
486224 248     * `./server/config` stores our Express JS config, header information and other middleware.
A 249     * `./server/config/environment` stores enviromnent specific config; such as connectivity to backend services like MongoDB.
867471 250     * `./tasks` is a collection of additional `Grunt` tasks which will be used in later exercises
486224 251     * `Grunt` is a taskrunner for use with Node.JS projects
3691a1 252     * `package.json` contains the dependency list and a lot of very helpful scripts for managing the app lifecycle
D 253
1d9ebc 254 2. A snippet of the npm scripts are shown below. There are application start scripts, build and test items which will be used in the build. The ones for MongoDB are just provided for convenience and require Docker installed to execute.
3691a1 255 ```json
D 256   "scripts": {
257     "start": "node server/app.js",
258     "dev": "./node_modules/.bin/grunt serve",
259     "jshint": "./node_modules/.bin/grunt jshint",
260     "clean": "rm -rf reports package-contents*",
261     "package": "zip -r package-contents.zip package-contents",
262     "test": "node_modules/.bin/nyc node_modules/.bin/mocha server/**/*.spec.js --exit",
263     "mongo" : "docker run -i -d --name mongo-local -p 27017:27017 mongo",
264     "mongo:drop" : "npm run mongo:stop && docker rm mongo-local",
265     "mongo:stop" : "docker stop mongo-local",
266     "mongo:start" : "docker start mongo-local"
267   },
f9e311 268 ```
A 269
514d1d 270 2. To run the application; start a new instance of the MongoDB by running the following. This will pull a mongodb image from Dockerhub and then start it for our API to connect to. 
3691a1 271 ```bash
ad8436 272 npm run mongo
3691a1 273 ```
D 274 <p class="tip">
e8cd20 275 NOTE - `npm run mongo:drop` is used to completely remove the running container. `npm run mongo:stop` & `npm run mongo:start` will preserve data in the container
3691a1 276 </p>
D 277
278 2. Fire up the `todolist-api` by running.
279 ```bash
ad8436 280 npm run start
3691a1 281 ```
D 282 ![node-app-started](../images/exercise2/node-app-started.png)
283
486224 284 2. Check things are up and running by testing the API with a `curl`. The API should return some seeded data (stored in `server/config/seed.js`)
3691a1 285 ```bash
ad8436 286 curl localhost:9000/api/todos
3691a1 287 ```
D 288 ```json
289 [{
290     "_id": "5ac8ff1fdfafb02138698948",
291     "title": "Learn some stuff about MongoDB",
292     "completed": false,
293     "__v": 0
294   },
295   {
296     "_id": "5ac8ff1fdfafb02138698949",
297     "title": "Play with NodeJS",
298     "completed": true,
299     "__v": 0
300 }]
301 ```
302
486224 303 2. Now let's check out `todolist-fe` app by reloading the browser. We should now see our dummy front end data is replaced by the backend seed data. Adding new todos will add them in the backend, these will persist when the page is refreshed.
3691a1 304 ![fullstack-app](../images/exercise2/fullstack-app.png)
D 305
306
273e4c 307 ### Part 2 - Create a NodeJS Build slave
374f63 308 > _In this exercise; we will create a build configuration to generate a slave for Jenkins to use in it's builds_
273e4c 309
7dca92 310 3. In order for Jenkins to be able to run `npm` builds and installs as we have done locally, we must configure a `jenkins-build-slave` for Jenkins to use. This slave will be dynamically provisioned when we run a build. It needs to have NodeJS and npm installed in it. In your `enablement-ci-cd` repository, checkout the template and configuration. This will bring in the template, the params & the `Dockerfile`.
273e4c 311 ```bash
ad8436 312 git checkout exercise2/jenkins-slave docker/ templates/ params/jenkins-slave-npm
273e4c 313 ```
D 314
d82125 315 3. Open the `params/jenkins-slave-npm` file and update `<GIT_URL>` accordingly. This set of parameters will clone from the enablement repo and run a docker build of the Dockerfile stored in `docker/jenkins-slave-npm`.
273e4c 316 ```bash
d82125 317 SOURCE_REPOSITORY_URL=<GIT_URL>
273e4c 318 SOURCE_CONTEXT_DIR=docker/jenkins-slave-npm
1937a3 319 NAME=jenkins-slave-npm
273e4c 320 ```
D 321
b92135 322 3. Create an item in the `inventory/host_vars/ci-cd-tooling.yml` under the `ci-cd-builds` object to run the template with.
273e4c 323 ```yaml
1937a3 324   - name: "jenkins-slave-npm"
b92135 325     namespace: "{{ ci_cd_namespace }}"
D 326     template: "{{ playbook_dir }}/templates/jenkins-slave-generic-template.yml"
327     params: "{{ playbook_dir }}/params/jenkins-slave-npm"
273e4c 328     tags:
D 329     - jenkins-slave
330 ```
331 ![jenkins-slave-ansible](../images/exercise2/jenkins-slave-ansible.png)
332
e23af1 333 3. Commit your changes to the `enablement-ci-cd` repository!
D 334 ```bash
ad8436 335 git add .
D 336 ```
337 ```bash
338 git commit -m "ADD npm slave node for Jenkins"
339 ```
340 ```bash
341 git push
e23af1 342 ```
D 343
273e4c 344 3. Run the OpenShift Applier to trigger a build of this jenkins slave image.
D 345 ```bash
ad8436 346 ansible-playbook apply.yml -e target=tools \
273e4c 347      -i inventory/ \
D 348      -e "filter_tags=jenkins-slave"
349 ```
350
351 3. Verify the build executed successfully by logging into the cluster and checking the `builds` tab of the `<YOUR_NAME>-ci-cd` project.
352 ![jenkins-slave-npm-build](../images/exercise2/jenkins-slave-npm-build.png)
353
867471 354 3. You should now be able to apply the label `jenkins-slave-npm` to a build job to run a build on this newly created slave as we will see in the rest of this exercise
273e4c 355 <p class="tip">
D 356 NOTE - Jenkins may need to be restarted for the configuration to appear. To do this; navigate to your jenkins instance and add `/restart` to the url.
357 </p>
358
359 ### Part 3 - Add configs to cluster 
14268c 360 > _In this exercise; we will use the OpenShift Applier to drive the creation of cluster content required by the app such as MongoDB and the Apps Build / Deploy Config_
273e4c 361
ac41ef 362 4. On your terminal navigate to the root of the `todolist-fe` application. The app contains a hidden folder called `.openshift-applier`. Move into this `.openshift-applier` directory and you should see a familiar looking directory structure for an ansible playbook. 
d98f40 363 ```
D 364 .openshift-applier
365 ├── README.md
366 ├── apply.yml
367 ├── inventory
368 │   ├── group_vars
369 │   │   └── all.yml
370 │   └── hosts
371 ├── params
372 │   ├── build
373 │   ├── dev
3f9666 374 │   ├── ocp-pipeline
d98f40 375 │   └── test
D 376 ├── requirements.yml
377 └── templates
3f9666 378     ├── ocp-pipeline.yml
D 379     ├── todolist-fe-build.yml
380     └── todolist-fe-deploy.yml
d98f40 381 ```
2310e7 382 with the following
d1565e 383     * the `apply.yml` file is the entrypoint. 
d98f40 384     * the `inventory` contains the objects to populate the cluster with.
D 385     * the `params` contains the variables we'll apply to the `templates`
14268c 386     * the `templates` required by the app. These include the Build, Deploy configs as well as the services, health checks, and other app definitions.
d98f40 387
d1565e 388 4. There are a few updates to these manifests we need to make before applying the cluster content. In the `apply.yml` update the namespace `<YOUR_NAME>` variables accordingly. 
d98f40 389 ```yaml
D 390     ci_cd_namespace: donal-ci-cd
391     dev_namespace: donal-dev
392     test_namespace: donal-test
393 ```
394
d1565e 395 4. In the `params` folder update the `dev` and `test` files with the correct `<YOUR_NAME>` as you've done above. Example for the `dev` file: 
d98f40 396 ```bash
D 397 PIPELINES_NAMESPACE=donal-ci-cd
261f19 398 NAME=todolist-fe
d98f40 399 DEPLOYER_USER=jenkins
D 400 APP_TAG=latest
401 NAMESPACE=donal-dev
402 ```
403
14268c 404 4. With those changes in place we can now run the playbook. First install the `openshift-applier` dependency and then run the playbook (from the `.openshift-applier` directory). This will populate the cluster with all the config needed for the front end app.
d98f40 405 ```bash
ad8436 406 ansible-galaxy install -r requirements.yml --roles-path=roles
D 407 ```
408 ```bash
409 ansible-playbook apply.yml -i inventory/
d98f40 410 ```
69a4e4 411 ![ansible-success](../images/exercise2/ansible-success.png)
d98f40 412
14268c 413 4. Once successful, `commit` and `push` your changes to gitlab.
3f9666 414 ```bash
ad8436 415 git add .
D 416 ```
417 ```bash
418 git commit -m "UPDATE - change namespace vars to donal"
419 ```
420 ```bash
421 git push
3f9666 422 ```
14268c 423
176e08 424 4. Back on your terminal navigate to the root of the `todolist-api` application. Open the `.openshift-applier` directory. The same layout as seen in `todolist-fe` should be visible with one noticeable difference; the api requires `MongoDB` to connect to at runtime.
261f19 425
D 426 4. In the `apply.yml` update the namespace `<YOUR_NAME>` variables accordingly. For example:
427 ```yaml
428     ci_cd_namespace: donal-ci-cd
429     dev_namespace: donal-dev
430     test_namespace: donal-test
431 ```
432
433 4. In the `params` folder update the `dev` and `test` files with the correct `<YOUR_NAME>` as you've done above. Example for the `dev` file:
434 ```bash
435 PIPELINES_NAMESPACE=donal-ci-cd
436 NAME=todolist-api
437 DEPLOYER_USER=jenkins
438 APP_TAG=latest
439 NAMESPACE=donal-dev
440 ```
441
d362dc 442 4. Finally; run the Openshift Applier and install its dependencies to run the content into the cluster
261f19 443 ```bash
ad8436 444 ansible-galaxy install -r requirements.yml --roles-path=roles
D 445 ```
446 ```bash
447 ansible-playbook apply.yml -i inventory/
261f19 448 ```
273e4c 449
3f9666 450 4. Once successful, `commit` and `push` your changes to gitlab.
D 451 ```bash
ad8436 452 git add .
D 453 ```
454 ```bash
455 git commit -m "UPDATE - change namespace vars to donal"
456 ```
457 ```bash
458 git push
3f9666 459 ```
176e08 460
3f9666 461 4. Validate the build and deploy configs have been created in Openshift by checking `<YOUR_NAME> CI-CD builds` for the `BuildConfigs`
D 462 ![ocp-app-bc](../images/exercise2/ocp-app-bc.png)
463
464 4. Check `<YOUR_NAME>-dev` to see the deployment configs are in place
ee4a9b 465 ![ocp-app-dc](../images/exercise2/ocp-app-dc.png)
176e08 466
273e4c 467 ### Part 4 - Build > Bake > Deploy 
b15f06 468 > _In this exercise; we take what we have working locally and get it working in OpenShift_
273e4c 469
40ab32 470 This exercise will involve creating three stages (or items) in our pipeline, each of these is detailed below at a very high level. Move on to the next step to begin implementation.
D 471 * a *build* job is responsible for compiling and packaging our code:
472     1. Checkout from source code (`develop` for `<yourname>-dev` & `master` for `<yourname>-test`)
473     2. Install node dependencies and run a build / package
474     3. Send the package to Nexus
475     4. Archive the workspace to persist the workspace in case of failure
476     4. Tag the GitLab repository with the `${JOB_NAME}.${BUILD_NUMBER}` from Jenkins. This is our `${BUILD_TAG}` which will be used on downstream jobs.
477     5. Trigger the `bake` job with the `${BUILD_TAG}` param
478 * a *bake* job should take the package and put it in a Linux Container
479     1. Take an input of the previous jobs `${BUILD_TAG}` ie `${JOB_NAME}.${BUILD_NUMBER}`.
480     2. Checkout the binary from Nexus and unzip it's contents
481     3. Run an oc start-build of the App's BuildConfig and tag it's imagestream with the provided `${BUILD_TAG}`
482     4. Trigger a deploy job using the parameter `${BUILD_TAG}`
483 * a *deploy* job should roll out the changes by updating the image tag in the DC:
484     1. Take an input of the `${BUILD_TAG}`
485     2. Patch / set the DeploymentConfig to the image's `${BUILD_TAG}`
486     3. Rollout the changes
487     4. Verify the deployment
19df4d 488 * We will now go through these steps in detail.
273e4c 489
752f2a 490 #### 4a - Build
273e4c 491
261f19 492 5. With the BuildConfig and DeployConfig in place for both our apps (`*-fe` & `*-api`) from previous steps; Log into Jenkins and create a `New Item`. This is just jenkins speak for a new job configuration. ![new-item](../images/exercise2/new-item.png)
273e4c 493
dd060d 494 5. Name this job `dev-todolist-fe-build` and select `Freestyle Job`. All our jobs will take the form of `<ENV>-<APP_NAME>-<JOB_PURPOSE>`. ![freestyle-job](../images/exercise2/freestyle-job.png)
273e4c 495
1937a3 496 5. The page that loads is the Job Configuration page and it can be returned to at anytime from Jenkins. Let's start configuring our job. To conserve space; we will make sure Jenkins only keeps the last builds artifacts. Tick the `Discard old builds` checkbox, then `Advanced` and set `Max # of builds to keep with artifacts` to 1 as indicated below 
D 497 ![keep-artifacts](../images/exercise2/keep-artifacts.png)
5a16fd 498
dd060d 499 5. Our NodeJS build needs to be run on the `jenkins-slave-npm` we created earlier. Specify this in the box labelled `Restrict where this project can be run` ![label-jenkins-slave](../images/exercise2/label-jenkins-slave.png)
0f4d08 500
19f0bd 501 5. On the Source Code Management tab, select the Git radio button, specify the endpoint for our GitLab `todolist-fe` Project and specify your credentials from the dropdown box. Set the Branch Specifier to `develop`. ![git-scm](../images/exercise2/git-scm.png)
0f4d08 502
dd060d 503 5. Scroll down to the Build Environment tab and select the `Color ANSI Console Output` checkbox ![ansi](../images/exercise2/ansi.png)
c3a934 504
19df4d 505 5. Move on to the Build section and select `Add build step`. From the dropdown select `Execute Shell`. On the box that appears; insert the following, to build package and deploy our app to Nexus:
c3a934 506 ```bash
D 507 set -o xtrace
7a3088 508 npm install
D 509 npm run build:ci:dev
510 npm run package
511 npm run publish
c3a934 512 ```
D 513 ![build-step](../images/exercise2/build-step.png)
514
dd060d 515 5. Scroll to the final section; the Post-build Actions. Add a new post-build action from the dropdown called `Archive the artifacts` and specify `**` in the box. This will zip the entire workspace and copy it back to Jenkins for inspection if needed. ![archive-artifacts](../images/exercise2/archive-artifacts.png)
c3a934 516
dd060d 517 5. On the Post-build Actions; Add another post-build action from the dropdown called `Git Publisher`. This is useful for tying the git check-in to the feature in your tracking tool to the built product.
c3a934 518     * Tick the box `Push Only If Build Succeeds`
D 519     * Add the Tag to push of 
520 ```bash
521 ${JOB_NAME}.${BUILD_NUMBER}
522 ```
523     * Specify the commit message to be
524 ```bash
525 Automated commit by jenkins from ${JOB_NAME}.${BUILD_NUMBER}
526 ```
19f0bd 527
A 528     * Check `Create New Tag` and set `Target remote name` to `origin`
c3a934 529 ![git-publisher](../images/exercise2/git-publisher.png)
D 530
19f0bd 531 5. Finally; add the trigger for the next job in the pipeline. This is to trigger the bake job with the current build tag. Add another post-build action from the dropdown called `Trigger parameterized build on other projects`. 
c3a934 532     * Set the project to build to be `dev-todolist-fe-bake` 
D 533     * Set the condition to be `Stable or unstable but not failed`. 
534     * Click Add Parameters dropdown and select Predefined parameters. 
535     * In the box, insert our BUILD_TAG as follows
536 ```bash
537 BUILD_TAG=${JOB_NAME}.${BUILD_NUMBER}
538 ```
539 ![param-trigger](../images/exercise2/param-trigger.png)
540 <p class="tip">
eaf747 541     NOTE - Jenkins might say "No such project ‘dev-todolist-fe-bake’. Did you mean ...." at this point. Don't worry; it's because we have not created the next job yet.
c3a934 542 </p>
D 543
dd060d 544 5. Hit `save` which will take you to the job overview page - and that's it; our *build* phase is complete!
c3a934 545
752f2a 546 #### 4b - Bake
40ab32 547
dd060d 548 5. Next we will setup our *bake* phase; which is a little simpler. Go to Jenkins home and create another Freestyle Job (as before) called `dev-todolist-fe-bake`.
c3a934 549
19f0bd 550 5. This job will take in the BUILD_TAG from the previous one so check the `This project is parameterized` box on the General tab.
eaf747 551     * Add string parameter type
19f0bd 552     * set the Name to `BUILD_TAG`. This will be available to the job as an Enviroment Variable.
eaf747 553     * You can set `dev-todolist-fe-build.` as the default value for ease when triggering manually.
D 554     * The description is not required but a handy one for reference would be `${JOB_NAME}.${BUILD_NUMBER} of previous build eg dev-todolist-fe-build.1232`
363974 555 <p class="tip">
A 556     NOTE - Don't forget to include the `.` after `dev-todolist-fe-build` in the Default Value box.
557 </p>
558
eaf747 559 ![param-trigger-bake](../images/exercise2/param-trigger-bake.png)
0f4d08 560
dd060d 561 5. This time set the `Restrict where this project can be run` label to `master`.
eaf747 562 <p class="tip">
363974 563     NOTE - `Master` is the default node that jobs run on. We don't want jenkins to execute the *bake* on any other nodes if the `master` is busy so it is always safer to specify it here.
eaf747 564 </p>
D 565
dd060d 566 5. There is no Git or SCM needed for this job so move down to the Build Environment and tick `Delete workspace before build starts`
eaf747 567
dd060d 568 5. Scroll down to the Build Environment tab and select the `Color ANSI Console Output` checkbox ![delete-ansi](../images/exercise2/delete-ansi.png)
eaf747 569
dd060d 570 5. Move on to the Build section and select `Add build step`. From the dropdown select `Execute Shell`. On the box the appears; insert the following, to pull the package from Nexus. We patch the BuildConfig with the Jenkins Tag to get traceablility from feature to source code to built item. Finally; the oc start-build command is run:
19f0bd 571 Remember to replace `<YOUR_NAME>` accordingly.
eaf747 572 ```bash
D 573 #!/bin/bash
436657 574 curl -v -f http://admin:admin123@${NEXUS_SERVICE_HOST}:${NEXUS_SERVICE_PORT}/repository/zip/com/redhat/todolist/${BUILD_TAG}/package-contents.zip -o package-contents.zip
eaf747 575 unzip package-contents.zip
8a47e6 576 oc project <YOUR_NAME>-ci-cd
eaf747 577 NAME=todolist-fe
62d4b9 578 oc patch bc ${NAME} -p "{\"spec\":{\"output\":{\"to\":{\"kind\":\"ImageStreamTag\",\"name\":\"${NAME}:${BUILD_TAG}\"}}}}"
eaf747 579 oc start-build ${NAME} --from-dir=package-contents/ --follow
D 580 ```
581 ![bake-step](../images/exercise2/bake-step.png)
582
dd060d 583 5. Finally; add the trigger for the next job in the pipeline. Add a post-build action from the dropdown called `Trigger parameterized build on other projects`.
eaf747 584     * Set the project to build to be `dev-todolist-fe-deploy`
D 585     * Set the condition to be `Stable`.
ac41ef 586     * Click Add Parameters dropdown and select `Current build parameters`. This will pass the `${BUILD_TAG}` to the downstream job which we will create next.
eaf747 587 ![downstream-trigger-deploy](../images/exercise2/downstream-trigger-deploy.png)
D 588
dd060d 589 5. Hit save! That's our *bake* phase done! Finally; on to our *deploy*
eaf747 590
752f2a 591 #### 4c - Deploy
40ab32 592
19f0bd 593 5. Next we will setup our *deploy* phase. This job is very similar in setup to the *bake* phase so this time go to Jenkins home and create `dev-todolist-fe-deploy` Job but scroll to the bottom and Copy from `dev-todolist-fe-bake`.
dd060d 594 ![copy-from](../images/exercise2/copy-from.png)
D 595
19f0bd 596 5. The only two differences between these jobs is the Build Step and there are no Post Build Actions. First to the Build tab and add the following to the shell box. The process for running the deploy is to tag the image created previously for use in the `ci-cd` namespace for use in the dev project. Then update the DeploymentConfig to use the Jenkins Tag which kicked the process off. Once successful; the changes are rolled out. Remember to change `<YOUR_NAME>` accordingly.
dd060d 597 ```bash
D 598 #!/bin/bash
599 set -o xtrace
600 # VARS
19f0bd 601 PIPELINES_NAMESPACE=<YOUR_NAME>-ci-cd
A 602 NAMESPACE=<YOUR_NAME>-dev
dd060d 603 NAME=todolist-fe
D 604 oc project ${NAMESPACE}
605 oc tag ${PIPELINES_NAMESPACE}/${NAME}:${BUILD_TAG} ${NAMESPACE}/${NAME}:${BUILD_TAG}
606 oc set env dc ${NAME} NODE_ENV=dev
607 oc set image dc/${NAME} ${NAME}=docker-registry.default.svc:5000/${NAMESPACE}/${NAME}:${BUILD_TAG}
608 oc rollout latest dc/${NAME}
609 ```
610 ![deploy-step](../images/exercise2/deploy-step.png)
611
ac41ef 612 5. When a deployment has completed; OpenShift can verify it's success. Add another step by clicking the `Add build Step` on the Build tab then `Verify OpenShift Deployment` including the following:
dd060d 613     * Set the Project to your `<YOUR_NAME>-dev`
D 614     * Set the DeploymentConfig to your app's name `todolist-fe`
615     * Set the replica count to `1`
616 ![verify-deployment](../images/exercise2/verify-deployment.png)
617
618 5. Finally; delete the Post Build Action to trigger another job (by hitting the red X). Save the configuration. We're almost ready to run the pipeline!
619
752f2a 620 #### 4d - Pipeline
40ab32 621
ac41ef 622 5. With our Jenkins setup in place; now move to our `todolist-fe` app's source code. We have to add our configuration to the frontend to tell it where the API layer will be hosted. Open the source in your favourite editor and navigate to `src/config/dev.js`.
D 623
624 5. Update `<YOUR_NAME>` accordingly with the route where the Todo List API will live when it is deployed, update the `somedomain` to the clusters domain. The correct full URL can also be found on the OpenShift Console; if you copy it from there remember to append `/api/todos` to the URL. For example:
40ab32 625 ![fe-dev-config](../images/exercise2/fe-dev-config.png)
D 626
ac41ef 627 5. Repeat this for `src/config/test.js` file. If you copy the URL from the previous step; change `dev` to `test`. Once done; commit your chanages and push them to GitLab
40ab32 628 ```bash
ad8436 629 git add .
D 630 ```
631 ```bash
632 git commit -m "ADD config for api"
633 ```
634 ```bash
635 git push
40ab32 636 ```
D 637
8a47e6 638 5. Back on Jenkins; We can tie all the jobs in the pipeline together into a nice single view using the Build Pipeline view. Back on the Jenkins home screen Click the + beside the all tab on the top.
D 639 ![add-view](../images/exercise2/add-view.png)
640
641 5. On the view that loads; Give the new view a sensible name like `dev-todolist-fe-pipeline` and select Build Pipeline
642 ![new-pipeline](../images/exercise2/new-pipeline.png)
dd060d 643
D 644 5. Set the Pipeline Flow's Inital Job to `dev-todolist-fe-build` and save.
645 ![pipeline-flow](../images/exercise2/pipeline-flow.png)
646
8a47e6 647 5. You should now see the pipeline view. Run the pipeline by hitting run (you can move onto the next part while it is running as it may take some time).
204a7b 648 ![dev-pipeline-view](../images/exercise2/dev-pipeline-view.jpeg)
dd060d 649
D 650 ### Part 5 - Backend Pipeline
19f0bd 651 > In this exercise we will use the Jobs created for the `todolist-fe` as a template to create a pipeline for the `todolist-api` app by copying the config.
dd060d 652
19f0bd 653 6. On Jenkins home; create a new job for our backend build called `dev-todolist-api-build`. Use the `Copy from` section to copy all the configuration from the `dev-todolist-fe-build`.
436657 654 ![copy-fe-build](../images/exercise2/copy-fe-build.png)
dd060d 655
436657 656 6. When this has loaded; find and replace both occurrences `-fe` with `-api` within the Job's configuration. Places to make sure you check are: 
D 657     * The GitLab project URL
658     * Projects to build on the Post Build Action
dd060d 659
19f0bd 660 6. On the Build tab; remove the `:dev` from the `npm run build:ci:dev` so the line reads.
A 661  The rest of the instructions can be left as they are.
436657 662 ```bash
7a3088 663 npm run build:ci
436657 664 ```
8a47e6 665 ![api-build-step](../images/exercise2/api-build-step.png)
dd060d 666
436657 667 6. Save the configuration for `dev-todolist-api-build`
dd060d 668
19f0bd 669 6. On Jenkins home; create a new job for our backend bake called `dev-todolist-api-bake`. Use the Copy from section to copy all the configuration from the `dev-todolist-fe-bake` as you've just done.
436657 670
D 671 6. When this has loaded; find and replace the occurrences `-fe` with `-api` within the Job's configuration. Places to make sure you check are:
672     * The BUILD_TAG default value and description
673     * NAME in the execute shell step
674     * Projects to build on the Post Build Action
675
676 6. Save the configuration for `dev-todolist-api-build`
677
678 6. On Jenkins home; create a new job for our backend build called `dev-todolist-api-deploy`. Use the Copy from section to copy all the configuration from the `dev-todolist-fe-deploy` as you've just done.
679
680 6. When this has loaded; find and replace the occurrences `-fe` with `-api` within the Job's configuration. Places to make sure you check are:
681     * The BUILD_TAG default value and description
682     * NAME in the execute shell step
683     * The name of the DeploymentConfig to validate in the Verify OpenShift Deployment
684
1937a3 685 6. Save the configuration for `dev-todolist-api-deploy` and that's it for wiring together our `todolist-api` pipeline.
436657 686  
8a47e6 687 6. Run the `dev-todolist-api-build` to trigger the backend pipeline. While this is building, check our front end app and see if it has deployed successfully.
D 688
ac41ef 689 6. To check the deployment in OpenShift; open the console and go to your `dev` namespace. You should see the deployment was successful; hit the URL to open the app (the screenshot below has both apps deployed).
8a47e6 690 ![ocp-deployment](../images/exercise2/ocp-deployment.png)
D 691
692 6. If it has been a success we should see our dummyData. This is because there is no backend deployed.
436657 693 ![no-backend-app](../images/exercise2/no-backend-app.png)
D 694
f9e311 695 6.  When `dev-todolist-api-build` has completed we should see the sample data has changed on refresh.
436657 696 ![with-backend-app](../images/exercise2/with-backend-app.png)
0f4d08 697
f50a94 698 ### Part 6 - GitLab Webhooks
b770c6 699 > _In this exercise we will link GitLab to Jenkins so that new build jobs are triggered on each push to the `develop` branch._
13e8fd 700
b770c6 701 <p class="tip" >
570732 702 NOTE - This section is optional! Git webhooks are useful but not needed for Enablement completion.
b770c6 703 </p>
D 704
1937a3 705 7. In order to allow GitLab trigger Jenkins (because of the OpenShift Auth Plugin), we need to allow the `Anonymous` user trigger builds. Head to your Jenkins Dashboard and click on `Manage Jenkins` on the left hand side. Then scroll down and click `Configure Global Security`. Alternatively, type in `https://jenkins-<YOUR_NAME>-ci-cd.apps.some.domain.com/configureSecurity/` . You should see a screen like so:
f50a94 706 ![jenkins-global-security](../images/exercise2/jenkins-global-security.png)
A 707
708 7. Scroll down to the `Authorization` section and allow `Anonymous` to create jobs. Do this by navigating through the matrix of checkboxes and check `Build` and `Cancel` under the Job heading. Leave all other user behaviour as is. Anonymous is the user that GitLab will act as so this allows the WebHook to trigger builds. (The screenshot has been cropped to bring Job further to the left.) Hit `Save` or `Apply`.
709 ![jenkins-anon-permissions](../images/exercise2/jenkins-anon-permissions.png)
710
30f5d9 711 7. Go to your `dev-todolist-fe-build` and head to the `configure` section (`https://jenkins-<YOUR_NAME>-ci-cd.apps.some.domain.com/job/dev-todolist-fe-build/configure`). Scroll down to the `Build Triggers` section and check the `Build when a change is pushed to GitLab` box. Leave all the other settings as they are but copy the `GitLab webhook URL`. `https://jenkins-<YOUR_NAME>-ci-cd.apps.some.domain.com/project/dev-todolist-fe-build`. Remember to Save and Apply this change.
c50c7b 712 ![jenkins-build-triggers-gitlab](../images/exercise2/jenkins-build-triggers-gitlab.png)
13e8fd 713
db60b7 714 7. Switch over to GitLab and select your `todolist-fe` repository. On the left hand task bar hover over the settings cog and select `integrations`. (`https://gitlab-<YOUR_NAME>-ci-cd.apps.some.domain.com/<YOUR_NAME>/todolist-fe/settings/integrations`)
c50c7b 715 ![gitlab-integrations](../images/exercise2/gitlab-integrations.png)
13e8fd 716
c50c7b 717 7. Paste the `GitLab webhook URL` that we copied earlier into the `URL` field. Check Push events as the trigger, and make sure you `uncheck` the `SSL verification` checkbox. Click Add webhook at the bottom.
A 718 ![gitlab-integrations-details](../images/exercise2/gitlab-integrations-details.png)
13e8fd 719
c50c7b 720 7. Before we move on let's test the webhook. Select the Test drop down and click `Push events`. This will trigger the test and return a status code at the top of the page. If all goes well it should be a cool blue 200.
A 721 ![gitlab-integrations-details](../images/exercise2/gitlab-webhook-test.png)
13e8fd 722
c50c7b 723 7. We can now test this properly by heading into the `todolist-fe` repository through <YOUR_FAVOURITE_EDITOR>. Make a small change to your code, then commit and push it, ensuring you're on the develop branch. Then head over to Jenkins and wait until the `dev-todolist-fe-build` job has been triggered.
13e8fd 724
30f5d9 725 7. All that's left to do is to repeat the same steps for `todolist-api` (Starting from step 3):
c50c7b 726 Create Build Trigger: 
db60b7 727 `https://jenkins-<YOUR_NAME>-ci-cd.apps.some.domain.com/job/dev-todolist-api-build/configure`
c50c7b 728 Create GitLab Integration:
db60b7 729 `https://gitlab-<YOUR_NAME>-ci-cd.apps.some.domain.com/donal/todolist-api/settings/integrations`
c50c7b 730 Check your build status and you should see something like this. With `Started by Gitlab push by <YOUR_NAME>`:
A 731 ![jenkins-gitlab-webhook-success](../images/exercise2/jenkins-gitlab-webhook-success.png)
13e8fd 732
c50c7b 733 7. We now have a working GitLab webhook so any time we push code it will automatically build! Next up we'll show you how to add tests to your pipeline.
b770c6 734
5a16fd 735 _____
D 736
0f4d08 737 ## Extension Tasks
a4f42c 738 > _Ideas for go-getters. Advanced topic for doers to get on with if they finish early. These will usually not have a solution available and are provided for additional scope._
0f4d08 739
436657 740 - Pipeline Tasks
f9e311 741     * Add pipeline for `master` branch for each project. Use `test-` instead of `dev-` across all config and names in the pipeline
A 742     * Do the `.openshift-applier` steps as part of the pipeline for greater end to end automation.
c3a934 743 - Promote build
f9e311 744     * Create a _promote-to-uat_ phase after the `master` branch deploy
a4f42c 745     * Create a `uat` env using the OpenShift Applier as seen before
c3a934 746     * Tag and promote the image without rebuilding after the `test-**-deploy`
261f19 747 - MongoDB tasks
c3a934 748     * Add MongoDB Stateful set for the UAT environment (or test)
D 749     * Inject MongoDB config into the NodeJS app using config map & secrets.
a4f42c 750     * Improve the security of the DB by making the user /passwords randomly generated
c3a934 751 - Setup Nexus as an `npm` mirror registry and use it in the builds to speed up the build time
0f4d08 752
D 753 ## Additional Reading
5a16fd 754 > List of links or other reading that might be of use / reference for the exercise
f2b1b4 755
5a16fd 756 ## Slide links
9eed0b 757
4f0295 758 - [Intro](https://docs.google.com/presentation/d/1t1CONuy-_IRPZYmU010Qgk2rshiDJTennvLyQR8GllE)
RH 759 - [Wrap-up](https://docs.google.com/presentation/d/1kZ8SV6iJnrKk_AqPpyPuNZifv7VzItHOB9HYdOnNJjI)
3207b9 760 - [All Material](https://drive.google.com/drive/folders/1lf66ks2tT0eQ4A9RSU48u0ZhvBXzoHWJ)