Skip to content
ImagineWorld

The Release and Configure Phase

node_idnode-book_mastering-gitlab-12_chapter-11-the-release-and-configure-phase
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num11
chapter_titleThe Release and Configure Phase
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 11 — The Release and Configure Phase

Section titled “Chapter 11 — The Release and Configure Phase”

In this chapter, we will take automation one step further than before. We will start by showing you how to deploy your code to a staging environment after testing and ultimately to production. This is a basic concept in the DevOps transition. We will finish this chapter by explaining about Auto DevOps, a way to fully automate the deployment to a Kubernetes cluster with integrated testing, security scanning, and even performance tests. This is considered the optimal DevOps path by GitLab.

In this chapter, we will cover the following topics:

  • Continuous Deployment with deployment to Amazon Web Services
  • Auto DevOps with the use of a Kubernetes cluster in Google Cloud

To follow along with the instructions in this chapter, please download this book’s GitHub repository, along with the examples, at https://github.com/PacktPublishing/Mastering-GitLab-12/tree/master/Chapter11.

Here, in the Chapter11 directory, you will find two applications that are used for the examples in this chapter.

To run certain automation scripts, you need an Amazon Web Services (AWS) account, which can be created here: https://aws.amazon.com/free/.

For the instructions on how to create a cluster on the Google Kubernetes Engine (GKE), you also need a Google account that you can use with Google Cloud, which you can create here: https://cloud.google.com/products/search/apply/.

Continuous Deployment, as explained in Chapter 9, GitLab Vision – The Whole Toolchain in One Application, is an extension of Continuous Integration, aiming at minimizing cycle time; that is, the time it takes to produce one new line of code by a development team and it being deployed in the production environment. We will demonstrate this practice by deploying the eventmanager Ruby code to Amazon Elastic Beanstalk, a service for deploying and scaling web applications and services that have been developed with a multitude of languages on different platforms.

There is also the option to create Ruby environments running a Puma web server. Let’s log in to the AWS web console (https://console.aws.amazon.com/console/) and click on the Services tab. We can use the search option to find something within the huge range of services that are available within the Amazon Cloud:

Type beanstalk into the Find Services widget and click the link it finds. Choose to create a new environment:

The environment will deploy. When it’s finished, you can view it in the dashboard:

We are going to use CI/CD for our Continuous Deployment strategy. First, we will create a .gitlab-ci.yml file with different stages (staging and production). The first part of this file will define the variables to be used in the different stages. Here, we will define a S3_BUCKET_NAME, which will be used to copy a deployment package to, a REGION to specify where the service will be hosted, and finally an APPNAME, which corresponds to the app name in Amazon Beanstalk:

variables:
S3_BUCKET_NAME: "elasticbeanstalk-eu-west-1-513361393569"
REGION: "eu-west-1"
APPNAME: "eventmanager"

We need to run our tests before we can advance to the next stage. In the following code, on the second line, we specify a Docker image with Ruby installed to run our tests. In the script section, run the default rspec tests:

test:
image: ruby:latest
stage: test
script: "bundle install;rspec"

This step will use the dpl tool (https://github.com/travis-ci/dpl) to interface with Amazon Beanstalk and deploy to the staging environment:

deploy_staging:
stage: deploy
script:
- echo "Deploy to staging server"
image: ruby:latest
environment:
name: staging
url: http://staging.gbnfcg9st9.eu-west-1.elasticbeanstalk.com
script:
- echo "Deploying to staging"
- gem install dpl
- dpl --provider=elasticbeanstalk --access-key-id=$AWS_ACCESS_KEY_ID --secret-access-key=$AWS_SECRET_ACCESS_KEY --app=$APPNAME --env=$CI_ENVIRONMENT_NAME --region=$REGION 13 --bucket_name=$S3_BUCKET_NAME
only:
- cd

As you can see, we also need to get AWS credentials from somewhere ($AWS_ACCESS variables). We can define these variables in the CI/CD environment variables section of the settings of the eventmanager project. Now, we will use a feature called multiproject pipelines, which has been available since GitLab 11.8. We are going to define a bridge job, which will run the default pipeline in the eventmanager-documentation project:

deploy_documentation:
stage: deploy
variables:
ENVIRONMENT: staging
trigger: marketing/eventmanager-documentation

We also want to deploy to production. We created a separate Beanstalk instance for that with an environment named production. But what if we want the last step to remain a manual one? Then we need to define a control structure with when:manual, which means that the step has to be manually initiated:

deploy to production:
stage: deploy
environment: production
when: manual
image: ruby:latest
script:
- echo "Deploying to production"
- gem install dpl
- dpl --provider=elasticbeanstalk --access-key-id=$AWS_ACCESS_KEY_ID --secret-access-key=$AWS_SECRET_ACCESS_KEY --app=$APPNAME --env=$CI_ENVIRONMENT_NAME --region=$REGION 10 --bucket_name=$S3_BUCKET_NAME
only:
- cd

If you save this .gitlab-ci.yml file (and commit and push it), it will start a deployment. If you click on the pipeline, you will get an overview of the jobs:

In the preceding screenshot, you can see the stages. First, there’s the test stages, which run the rspec tests. The deploy_documentation job triggers a downstream pipeline (eventmanager-documentation). Simultaneously, the deployment to the staging area starts. Let’s click on the job that starts:

By looking at the log file of the deployment to the staging area, you will find the following code:

Running with gitlab-runner 11.9.2 (fa86510e)
on Computer1 8REjeNy3
Using Docker executor with image ruby:latest ...
Pulling docker image ruby:latest ...
Using docker image sha256:f39c31795d257be1b6344eefdc324180a90ffb9b82a52d171982703dd26f549c for ruby:latest ...
Running on runner-8REjeNy3-project-3-concurrent-0 via Joosts-iMac-Pro.fritz.box...
Reinitialized existing Git repository in /builds/it/eventmanager/.git/
Clean repository
Fetching changes...
fatal: remote origin already exists.
Checking out 2dbf81c9 as cd...
...
Skipping Git submodules setup
$ echo "Deploying to staging"
Deploying to staging

The container installs the dpl dependency:

$ gem install dpl
Successfully installed dpl-1.10.8
1 gem installed

It then runs the deployment:

dpl --provider=elasticbeanstalk --access-key-id=$AWS_ACCESS_KEY_ID --secret-access-key=$AWS_SECRET_ACCESS_KEY --app=$APPNAME --env=$CI_ENVIRONMENT_NAME --region=$REGION --bucket_name=$S3_BUCKET_NAME

The dpl tool only runs if the Git repository is clean:

Preparing deploy
Cleaning up git repository with \`git stash --all\`. If you need build artifacts for deployment, set \`deploy.skip_cleanup: true\`. See https://docs.travis-ci.com/user/deployment#Uploading-Files-and-skip_cleanup.
No local changes to save
Deploying application
No stash found.
Job succeeded

There is no feedback about the upload except for the message stating that the application has been deployed. You can verify this deployment by visiting the URL that is mentioned in the Beanstalk environment that was created with the AWS console.

You can manually trigger the deploy job to production from the diagram, which is where we saw the play button.

In GitLab, you can go to Operations | Environments | Production to view the deployments. You can also roll back to an earlier release:

In this section, we have showed you how to implement a deployment pipeline using Gitlab CI and GitLab runners. You can create them just by using shell scripts and make them as elaborate as you want by using multiproject pipelines and advanced syntax.

By default, Auto DevOps is turned on for every project. It is essentially a very elaborate .gitlab-ci.yml file, which outlines the entire DevOps pipeline from the creating phase onward.

It fits in the GitLab vision of providing one application to collaborate on the entire DevOps life cycle of an application.

As we mentioned earlier, Auto DevOps is enabled by default for every project, but if you want to disable it or configure it differently, you need to go into the settings, which you can find by going to Settings | CI/CD | Auto DevOps:

As you can see, you need to configure a Kubernetes cluster to make this all work.

Another setting you can manage here is the deployment strategy. The default setting is that the pipeline deploys up to production. This might not be the strategy you want for your enterprise. You can use an incremental rollout as well.

You should also note that a deployment pipelines is fully automated until the last step, which is production. You can choose to leave that as a manual step.

To control the individual steps in the pipeline, you can view the Operations menu on the left-hand side. The following is a screenshot of the available operations:

When the first piece of code is pushed to the repository, an Auto DevOps pipeline is created. For the eventmanager project, this looks as follows:

Let’s evaluate each step of the Auto DevOps pipeline from the preceding screenshot.

The main idea is that, in the build phase, you prepare your code to run in a packaged way – in a Docker container that you built using a Dockerfile – via Heroku build packs.

For the eventmanager app, user1 created the following Dockerfile:

FROM ruby:2
COPY . /var/www/ruby
WORKDIR /var/www/ruby
RUN bundle install
CMD ["ruby","eventmanager.rb"]
EXPOSE 5000/tcp

As you can see from the first line of the preceding code, it pulls a basic Ruby-enabled Debian Linux image. It copies all the source code to a directory and goes there. Then, a bundle install is run, which installs all the Ruby dependencies that are needed. Finally, it starts the eventmanager app using the CMD command and exposes port 5000 to the outside world. It has to expose port 5000 because the default Helm chart that is used to deploy to Kubernetes assumes this port to run the application. It will be wired to port 80 or 443 after deployment.

The following code is for the log when the build phase is started:

Running with gitlab-runner 11.8.0 (4745a6f3)
on runner-gitlab-runner-7fd79f558b-2wx96 _drEv8rS
Using Kubernetes namespace: gitlab-managed-apps
Using Kubernetes executor with image registry.gitlab.com/gitlab-org/cluster-integration/auto-build-image/master:stable ...
Waiting for pod gitlab-managed-apps/runner-drev8rs-project-3-concurrent-0fvjtb to be running, status is Pending
...

It runs the Kubernetes executor and waits for a pod to be available.

When that happens, the build script is run. First, a login to the GitLab registry for this project is attempted (we need to push the build there afterwards):

$ /build/build.sh
Logging to GitLab Container Registry with CI credentials...
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Login Succeeded
...

Then, the build of the Docker image will start:

Building Dockerfile-based application...
Sending build context to Docker daemon 113.7kB
Step 1/6 : FROM ruby:2-alpine
2-alpine: Pulling from library/ruby
...

The built container image is pushed to the Docker registry for the eventmanager project:

Successfully built 5bd173d74f67
Successfully tagged
...
Job succeeded

When the Docker container image is stored in the registry, the subsequent phases will use the image and pull it. This concludes the build step. The next step is to run the code quality scan.

In this phase of the pipeline, a GitLab runner is used to scan your code for quality. You can find more information and an example of this in Chapter 10, Create Your Product, Verifying It, and Packaging It.

The next phase is still a part of the test stage. In this stage, a container instance is instantiated from your image and is scanned for vulnerabilities using clair (https://github.com/coreos/clair).

It will log in to the eventmanager Docker registry:

Running with gitlab-runner 11.8.0 (4745a6f3)
...
$ container_scanning
Logging to GitLab Container Registry with CI credentials...
...

Then, it will try to get a container with the scan tool in it:

Unable to find image 'arminc/clair-db:latest' locally
latest: Pulling from arminc/clair-db
...

When the container is running, it will start the scan:

2019/04/28 14:08:08 [0;32m[INFO] > Start clair-scanner
2019/04/28 14:08:37 [0;32m[INFO] > Server listening on port 9279
2019/04/28 14:08:37 [0;32m[INFO] > Analyzing 9cab74319993fe94abc345fa8933c789f4482b9644f9cb1d9758d31575ed1367
-----------------------------------------------------------+
| STATUS | CVE SEVERITY | PACKAGE NAME | PACKAGE VERSION | CVE DESCRIPTION |
| Unapproved | High CVE-2018-6551 | glibc | 2.24-11+deb9u4 | The malloc implementation in the GNU C Library (aka |
...

The default Ruby images uses a Debian image, which apparently has a lot of open vulnerabilities.

If you switch the basic image your Dockerfile uses to ruby:2-alpine, you will have a more basic Linux container, which should not give all of these errors. You will have to restart the pipeline (click retry in the list):

Waiting for clair daemon to start
...
contains NO unapproved vulnerabilities

When no vulnerabilities are found, the report is uploaded as an artifact and the job will succeed:

Uploading artifacts...
gl-container-scanning-report.json: found 1 matching files
..
Job succeeded

The created Docker image is now scanned for known vulnerabilities. When you want to whitelist anything that’s found, you can add them to a file called clair-whitelist.yml and add it to your repository.

This part of the pipeline scans your code for known security vulnerabilities in dependencies of your software. An example would be if you rely on third-party libraries that have known security issues. This will be explained in detail in the next chapter.

When this scan is complete, you will know whether the dependencies you use in your code are safe or not. It is also useful to know which licenses are used by dependencies because this can have a lot of consequences. We will explain this in the next section.

An issue that’s often overlooked by organizations is how to manage your intellectual property rights (IP). There are different open source licenses around; for example, there ones that are classified as permissive such as X11, Apache, and the BSD licenses. You also have the copyleft kind, such as the GPL, which are more restrictive and could make you share your derivative works. By using the license scanner, you ensure that you’re not using dependencies that have a negative impact on your intellectual property rights.

You will see the following output when the jobs runs:

Running with gitlab-runner 11.8.0 (4745a6f3)
on runner-gitlab-runner-7fd79f558b-2wx96 _drEv8rS
Using Kubernetes namespace: gitlab-managed-apps
Using Kubernetes executor with image registry.gitlab.com/gitlab-org/security-products/license-management:$CI_SERVER_VERSION_MAJOR-$CI_SERVER_VERSION_MINOR-stable ...

This scan is run from a container, but that runs code and parses your project:

$ license_management
mesg: ttyname failed: Inappropriate ioctl for device
Added development to the ignored groups
Added test to the ignored groups
Fetching gem metadata from https://rubygems.org/.........

This will analyze and upload a report artifact:

Running license_finder in /it/eventmanager
LicenseFinder::Bundler: is active
Uploading artifacts...
gl-license-management-report.json: found 1 matching files
Uploading artifacts to coordinator... ok id=478 responseStatus=201 Created token=HjYg-s1y
Job succeeded

The result is also viewable from the merge request widget.

As you can see, the inclusion of a license check in the pipeline can be very useful. Is it better to know as early as possible whether you are using dependencies that affect the way you can distribute your software. In the same parallel step of the pipeline, static security tests are conducted.

This part of the pipeline scans your code for known security issues, and is known as a static application security test. This will be explained in more detail in the next chapter. The final parallel step in the test stage is running the actual tests that are defined by your code.

In this pipeline, a specific container is started that clones the source code:

Running with gitlab-runner 11.8.0 (4745a6f3)
on runner-gitlab-runner-7fd79f558b-2wx96 _drEv8rS
Using Kubernetes namespace: gitlab-managed-apps
Using Kubernetes executor with image gliderlabs/herokuish:latest ...

It will try to detect the language that’s used. In our case, it finds a Ruby application, which is correct:

$ setup_test_db
$ cp -R . /tmp/app
$ /bin/herokuish buildpack test
-----> Ruby app detected
-----> Setting up Test for Ruby/Rack
-----> Using Ruby version: ruby-2.5.3
-----> Installing dependencies using bundler 1.15.2

After installing the necessary dependencies, it will run the rake test task:

-----> Running test: bundle exec rspec
...
Finished in 0.03197 seconds (files took 0.22688 seconds to load)
3 examples, 0 failures

In our case, no errors were detected. You can check which tests are run in your tests folder.

Of course, the tests that are run are written by yourself, so you determine how much value they have. When they are finished, the next stage is to deploy to production, which is covered in the next section.

The default Auto DevOps pipeline will deploy your code to production after it finishes the test stage. Various environment variables are available that you can set that will control the autoscaling of your replica pods. The heavy lifting in this phase is performed by the auto-deploy-app Helm chart. You can also provide your own chart by adding it to a .chart directory in your project or by setting AUTO_DEVOPS_CHART combined with the AUTO_DEVOPS_CHART_REPOSITORY environment variable with the URL to your custom chart. It will create several things:

  • A deploy token
  • A Prometheus monitoring instance that’s wired for your application

Let’s run the following code through the log file:

Running with gitlab-runner 11.8.0 (4745a6f3)
on runner-gitlab-runner-7fd79f558b-2wx96 _drEv8rS
Using Kubernetes namespace: gitlab-managed-apps
Using Kubernetes executor with image alpine:latest ...

This checks the artifacts of the previous jobs and performs a check on the Kubernetes domain. It will install dependencies for minimal Helm execution:

Checking out 08222854 as master...
Skipping Git submodules setup
Downloading artifacts for code_quality (477)...
Downloading artifacts from coordinator... ok id=477 responseStatus=200 OK token=zxQGxCFW
Downloading artifacts for license_management (478)...
Downloading artifacts from coordinator... ok id=478 responseStatus=200 OK token=HjYg-s1y
Downloading artifacts for container_scanning (481)...
Downloading artifacts from coordinator... ok id=481 responseStatus=200 OK token=hErz9aWj
$ # Auto DevOps variables and functions # collapsed multi-line command
$ check_kube_domain
$ install_dependencies

The next step is to download the required chart (auto-deploy-app chart or custom):

$ download_chart

Next, we need to ensure that a namespace is defined (which is usually the Kubernetes cluster name you used):

$ ensure_namespace

Now, it’s time to initialize tiller (the Helm server):

initialize_tiller

Here, a secret to access the registry is created:

create_secret

Finally, the deployment can start:

$ deploy secret "production-secret"
deleted secret/production-secret replaced
Deploying new release...
Release "production" has been upgraded.
Happy Helming! ...

After the deployment, you will see feedback about the URL where the application is running. The name is created by appending the namespace to the project name and the domain wildcard where the cluster is running:

NOTES:
Application should be accessible at: http://it-eventmanager.kubernetes.joustie.nl
Waiting for deployment "production" rollout to finish: 0 of 1 updated replicas are available...
deployment "production" successfully rolled out
$ delete canary
$ delete rollout
$ persist_environment_url
Uploading artifacts...
environment_url.txt: found 1 matching files
Uploading artifacts to coordinator... ok id=482 responseStatus=201 Created token=koT8yujj
Job succeeded

If you have configured kubectl to use the context of your GKE cluster, on the command line, you can verify whether your deployments took place:

Joosts-iMac-Pro:Part3 joostevertse$ kubectl get pods --all-namespaces

The list of pods should show you the pods that were started:

NAME READY STATUS RESTARTS AGE
eventmanager production-6b9db68f6f-hrwzv 1/1 Running 0 11h
eventmanager production-postgres-5b5cf56747-xngbk 1/1 Running 0 11h

By default, a postgres instance is started as well, and you can fine-tune your installation to use it if you need it. You can find more information about that here: https://docs.gitlab.com/ee/topics/autodevops/#postgresql-database-support. There are also other pods in the list, and they are all part of the deployment:

certmanager-cert-manager-6c8cd9f9bf-8kbf8 1/1 Running 0 11h
ingress-nginx-ingress-controller-ff666c548-n2s84 1/1 Running 0 11h
ingress-nginx-ingress-default-backend-677b99f864-bnk8c 1/1 Running 0 11h
runner-gitlab-runner-7fd79f558b-2wx96 1/1 Running 0 11h
tiller-deploy-6586b57bcb-t6zql 1/1 Running 0 11h

The eventmanager application can be viewed by going to http://it-eventmanager.kubernetes.joustie.nl:

Now, we have a running application that is being tested and monitored. The next and final step is to run a performance check on the production environment. Again, we can use our Kubernetes cluster to spawn a test container for it and run performance tests on it, which is the subject of the next section.

In the log file for the performance job, you can see that Kubernetes is again used to spawn an instance to use:

Running with gitlab-runner 11.8.0 (4745a6f3)
on runner-gitlab-runner-7fd79f558b-2wx96 _drEv8rS
Using Kubernetes namespace: gitlab-managed-apps

The job connects to GitLab.com and verifies the version of the image it should pull. It uses the sitespeed.io container to do this (https://hub.docker.com/r/sitespeedio/sitespeed.io/):

$ performance
Connecting to gitlab.com (35.231.145.151:443)
index.js 100% |********************************| 1614 0:00:00 ETA
Unable to find image 'sitespeedio/sitespeed.io:6.3.1' locally
6.3.1: Pulling from sitespeedio/sitespeed.io
...

Inside the container, it tries to measure browser performance with Chrome and Firefox:

Google Chrome 63.0.3239.132
Mozilla Firefox 54.0.1
[2019-04-25 21:42:41] INFO: Versions OS: linux 4.14.91+ nodejs: v8.9.4 sitespeed.io: 6.3.1 browsertime: 2.1.4 coach: 1.2.0

It will do a subsequent number of runs:

[2019-04-25 21:42:41] INFO: Starting chrome for analysing http://it-eventmanager.kubernetes.joustie.nl 3 time(s)
[2019-04-25 21:42:41] INFO: Testing url http://it-eventmanager.kubernetes.joustie.nl run 1
[2019-04-25 21:42:51] INFO: Testing url http://it-eventmanager.kubernetes.joustie.nl run 2
[2019-04-25 21:43:00] INFO: Testing url http://it-eventmanager.kubernetes.joustie.nl run 3
[2019-04-25 21:43:09] INFO: 2 requests, 586 bytes, backEndTime: 39ms (±1.87ms), firstPaint: 119ms (±2.43ms), firstVisualChange: 0ms (±0.00ms), DOMContentLoaded: 103ms (±3.06ms), Load: 104ms (±3.06ms), speedIndex: 0 (±0.00), visualComplete85: 0ms (±0.00ms), lastVisualChange: 0ms (±0.00ms), rumSpeedIndex: 119 (±2.25) (3 runs)
[2019-04-25 21:43:13] INFO: HTML stored in /sitespeed.io/sitespeed-results
[2019-04-25 21:43:13] INFO: Finished analyzing http://it-eventmanager.kubernetes.joustie.nl
...

The results will be saved as a HTML report artifact, as well as a JSON file:

Uploading artifacts...
performance.json: found 1 matching files
sitespeed-results/: found 64 matching files
Uploading artifacts to coordinator... ok id=483 responseStatus=201 Created token=w-R8qzFw
Job succeeded

The following code is a part of the JSON file:

{
"subject": "/",
"metrics": [
{
"name": "Transfer Size (KB)",
"value": "0.6",
"desiredSize": "smaller"
...

A nice HTML report is available too, which is part of the artifacts.

Auto DevOps is a very handy concept. It can give you a complete pipeline if your application stays close to standards and is not very complex. If you need more customization, you can use the template and fine-tune it to your needs.

This chapter demonstrated the potential of GitLab and the role it plays in the operations phase of a software product. You can develop your solution, test it, and eventually run it in an environment. Along the way, you can automate as much as possible. If you use the Auto DevOps feature, you will reach the full potential of the DevOps concept, which is currently a sought-after skill.

In the next chapter, we will look at the monitor and secure phases, which are the final phases in the DevOps pipeline.

  1. In which file do you define your deployments?
  2. What is the dpl tool?
  3. What is the GitLab vision for Auto DevOps?
  4. Where are the build artifacts stored at the end of the build phase (using Dockerfile)?
  5. What is the name of the container scanner that’s used in Auto DevOps?
  6. What is the name of the deployment Helm chart that’s used in Auto DevOps?
  7. How many pods are deployed for a production deploy?
  8. What is the name of the performance container?
  • Advanced Infrastructure Penetration Testing by Chiheb Chebbi: [
  • Learn Docker - Fundamentals of Docker 18.x by Gabriel N. Schenker:
  • AWS Automation Cookbook by Nikit Swaraj:
  • Hands-On Kubernetes on Azure by Gunther Lenz and Shivakumar Gopalakrishnan: