Are you tired of manually pushing code to production? Are you always searching through your BASH history to find the commands you used to test your code? Do you wish the process to merge code into production had a defined process? Well I have the solution for you! Introducing Gitlab CI/CD pipelines! With Gitlab you can setup Gitlab runners to create a CI/CD pipeline. A CI/CD pipeline will revolutionize your workflow to push code to production.
The purpose of this blog post is to provide instructions on how to setup the necessary components (Gitlab and Gitlab runners) to create a CI/CD pipeline. One of the deliverables from this blog post is Docker composes for Swarm and non-swarm deployments of Gitlab. Additionally, there are manual instructions on how to setup Gitlab runners on Ubuntu 20.04, Ubuntu 20.04 with Docker, Windows 10, Windows 10 with Docker, and macOS Big Sur. In addition, a Docker Registry is setup and integrated into the CI/CD pipeline for custom Docker images. The instructions and the infra-as-code provided in this post will create the foundation for future blogs that will contain a CI/CD component.
Goals
- Setup Gitlab stack with Docker Swarm
- Setup Gitlab runner on Windows
- Setup Gitlab runner on Linux
- Setup Gitlab runner on macOS
- Setup Gitlab runner on Docker Windows
- Setup Gitlab runner on Docker Linux
- Setup a Docker Registry with a self-signed HTTPS certificate
Update log
- September 24th 2021 – Updated Docker from Gitlab v13.8.1 to v14.3.0
Assumptions
- The means to generate DNS A records for each service.
- These services require DNS records and will NOT work without it!!!
- Docker Swarm or machine running Docker to run Gitlab
- The ability to run VMs but not required
- Access to a macOS machine or VM but not required
Background
What is Gitlab?
GitLab is a web-based DevOps lifecycle tool that provides a Git-repository manager providing wiki, issue-tracking and continuous integration and deployment pipeline features, using an open-source license, developed by GitLab Inc.
What is a Gitlab runner?
GitLab Runner is an application that works with GitLab CI/CD to run jobs in a pipeline. You can choose to install the GitLab Runner application on infrastructure that you own or manage. You can install GitLab Runner on several different supported operating systems or GitLab Runner can also run inside a Docker container. A more simplified explanation is a Gitlab runner is essentially a tool that executes the instructions defined in .gitlab-ci.yml
and sends the results back to Gitlab.
What is CI/CD?
Credit for the creation of this diagram goes to Valentin Despa: Udemy course: GitLab CI: Pipelines, CI/CD and DevOps for Beginners.
A CI/CD pipeline automates the process of delivering code from a developers machine to production. Obviously that statement is an over simplification of the process because the digram above illustrates numerous steps. This section is going to provide a high overview of the process to help you understand the general process needed for this blog post. CI/CD stands for continuous integration and continuous deployment, which as the acronym and the digram above illustrates is two distinct phases. Continuous integration is the process of integrating new code changes, validating the new code changes can still build/compile the application, and ensuring the new code passes a set of tests.
For example, let’s say you have a web application written in GoLang. As a developer you make some changes to the existing application on your local development machine and push the changes to Gitlab. Next, Gitlab will attempt to compile the existing code base with your changes. Assuming the compilation is successful, Gitlab will perform several tests on the newly compiled application to ensure the application is functioning as intended. If the tests are successful, the developer can merge the changes into the MAIN branch.
Now you might be asking what happens if this phase is unsuccessful? Using the example above, let’s say you initialize a variable that is not used. If you’re a GoLang developer you already know this will fail to compile but for this example let’s say the code is pushed to Gitlab. Gitlab will once again attempt to compile the code that contains your changes. However, the compilation will fail and typically the pipeline will stop running on the first occurrence of an error. Gitlab will provide the developer the ability to review the error produced. Until this issue is resolved Gitlab will not allow the new code to merged.
Continuous deployment is the process of again evaluating/testing the newly committed code, pushing the application to QA for further evaluation, and finally upon manual human interaction the code is pushed to production. Pushing to prod (production) means pushing your code to the environment so that your new code can be utilized by users. Again, as the digram above illustrates there is more to this process but hopefully this provided a high overview of the process. For a more in-depth explanation, I highly recommend checking out the following Udemy course: GitLab CI: Pipelines, CI/CD and DevOps for Beginners.
.gitlab-ci.yml stages
There really aren’t any official stages but the ones listed below outline a typical flow you might see:
- Pre-build – A set of actions to perform before building your application with the newly committed code. During this stage you might install the necessary tools, libraries, or dependencies to build your application.
- Build – A set of actions to build/compile your application with the newly committed code
- Test – A set of actions to run against your newly compiled/built application to ensure everything is functioning as intended
- Deploy – A set of actions that will only run when the build and test stages have successful completed their tasks without any errors. Upon completion, this stage will push the newly committed code to appropriate environment.
Network diagram
Generate OpenSSL private key and public cert
git clone https://github.com/CptOfEvilMinions/Gitlab-Automation
cd Gitlab-Automation
mv conf/tls/tls.conf.example conf/tls/tls.conf
vim conf/tls/openssl.conf
and set:- Replace
{{ base_domain }}
with your domain- My base_domain is
hackinglab.local
- My base_domain is
- Set the location information under
[ my_req_distinguished_name ]
C
– Set CoutryST
– Set stateL
– Set CityO
– Enter organization name
- Replace
openssl req -x509 -new -nodes -keyout conf/tls/tls.key -out conf/tls/tls.crt -config conf/tls/tls.conf
-
- Generate TLS private key and public certificate
-
Install Gitlab with Docker-compose v2.x
WARNING
The Docker-compose v2.x setup is for development use ONLY. The setup contains hard-coded credentials in configs and environment variables. For a more secure Docker deployment please skip to the next section to use Docker Swarm which implements Docker secrets.
WARNING
-
vim
.env
and setGITLAB_VERSION
– OPTIONAL – Set the version of Gitlab to use – Community edition or Enterprise editionGITLAB_ROOT_PASSWORD
– Set the Gitlab root user passwordPOSTGRES_GITLAB_PASSWORD
– Set Postgres Gitlab user passwordBASE_DOMAIN
– Set this to your domain
docker-compose -f docker-compose.yml build
docker-compose -f docker-compose.yml up -d
Install Gitlab with Docker-compose v3.x (Swarm)
Create secrets
openssl rand -base64 32 | tr -cd '[:alnum:]' | docker secret create gitlab-postgres-gitlab-password -
- Create password for Gitlab Postgres password
GITLAB_ROOT_PASSWORD=$(openssl rand -base64 32 | tr -cd '[:alnum:]')
- Generate Gitlab root password
echo $GITLAB_ROOT_PASSWORD
- Print Gitlab root password – record for later
echo -n $GITLAB_ROOT_PASSWORD | docker secret create gitlab-root-password -
- Create Gitlab root password
Docker start stack
docker stack deploy -c docker-compose-swarm.yml gitlab
docker service logs -f gitlab_nginx
- Monitor logs until NGINX prints
/docker-entrypoint.sh: Configuration complete; ready for start up
- Monitor logs until NGINX prints
Login into Gitlab WebGUI
- Open web browser to
https://<Docker IP addr>:8443
- Enter
root
as username - Enter
<Gitlab root password>
for password - Select “Sign in”
- Enter
Use Docker Registry
Push image to Registry
cd Gitlab-Automation
- Add self-signed certificate for the Docker Registry to your certificate store
- Instructions for macOS
security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/login.keychain conf/tls/tls.crt
- Add Registry certificate to the user’s local keychain
- Enter password
- Restart Docker Desktop on macOS
docker build -f docker/Dockerfile-ubuntu-custom -t ubuntu-custom .
docker image ls | grep ubuntu-custom
- Grab image ID
docker tag <custom Ubuntu image ID> registry.hackinglab.local:5000/custom-ubuntu
docker push registry.hackinglab.local:5000/custom-ubuntu
Pull image from Registry
Since the certificate for the Registry is self-signed Docker will NOT pull the image. The instructions below are how to add the self-signed certificate for the Docker Registry to the OS root cert store.
- SSH into Docker Swarm node
sudo su
openssl s_client -connect registry.<base_domain>:5000 2>/dev/null </dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /usr/local/share/ca-certificates/ca.crt
- Obtain the public certificate from the remote server
update-ca-certificates --fresh
- Instruct Ubuntu to add the new cert to the cert root store
systemctl restart docker
docker pull registry.<base_domain>:5000/custom-ubuntu
Install/Setup Gitlab runner
This section will cover how to setup a Gitlab runner on Windows 10, Windows 10 with Docker, Ubuntu 20.04, Ubuntu 20.04 with Docker, and macOS Big Sur. It should be noted that setting up a Gitlab runner on Docker is the optimal setup. Running a Gitlab runner on a VM will not provide a clean state between CI/CD runs. Meaning that if you have an Ubuntu 20.04 VM and the first CI/CD run installs Java 8 but the second run requires Java 7 you will have to uninstall Java 8 first to avoid dependency conflicts.
However, the other side of this coin is you can have a Gitlab runner with a pre-defined environment. Therefore the runs can assume that the correct Java version is installed and you just need to build and run the code. Docker containers provide the advantage that each container is a blank canvas ready to be crafted to the need of the run.
Obtain Gitlab runner register token
- Login in as a Gitlab admin
- Admin area > Overview > Runners
- Copy runners token
- Copy Gitlab runner URL
Install/Setup Gitlab runner on Docker
GITLAB_RUNNER_DOCKER_TOKEN=$(curl -k -s -X POST https://gitlab.<base_domain>:8443/api/v4/runners --form "token=<Gitlab runner registration token>" --form "description=Docker" | jq -r .token | tr -d '\n' )
- Generate Gitlab runner token
echo $GITLAB_RUNNER_DOCKER_TOKEN
cp conf/gitlab-runner/docker-gitlab-runner.toml.example conf/gitlab-runner/docker-gitlab-runner.toml
cat conf/gitlab-runner/docker-gitlab-runner.toml | sed 's#{{ gitlab_runner_url }}#https://gitlab.<base_domain>:8443/#g' | sed "s#{{ gitlab_runner_token }}#${GITLAB_RUNNER_DOCKER_TOKEN}#g" | docker secret create gitlab-runner-config -
- Create Gitlab runner config containing Gitlab runner token
docker stack deploy -c docker-compose-swarm-gitlab-runners.yml gitlab-runner
docker service logs -f gitlab-runner_gitlab-runner
- Admin area > Overview > Runners
- Select “Edit” for the runner
- Enter
linux,docker
into the tags field - Select “Save changes”
- Enter
Install/Setup Gitlab runner on Windows 10
Install GIT
- Log into Windows
- Open Powershell as Administrator
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
choco install git
- Install GIT
Install/Setup Gitlab runner
- Log into Windows
- Open Powershell as Administrator
mkdir 'C:\Program Files\gitlab-runner'
- Make a directory for Gitlab
cd 'C:\Program Files\gitlab-runner'
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-windows-amd64.exe -OutFile gitlab-runner.exe
- Download Gitlab runner
- Open Chrome
- Browse to Gitlab homepage
- Select the “Not secure” button next to the address bar then “Certificate”
- Select. “Details” tab
- Select “Copy to file”
- Follow the instructions to export the certificate to the Desktop
- Select “Base-64 encoded X.509 (.CER)” for format
- Move the public certificate to
C:\Program Files\gitlab-runner
- Return to Powershell terminal
.\gitlab-runner.exe register --tls-ca-file .\gitlab.cer
- Register Gitlab runner
- Enter
https://gitlab.<base_domain>:8443
- Enter
<registration token>
- Enter
WindowsVM
for description - Enter
windows, win10_1909
for tags - Enter
shell
for executor
.\gitlab-runner.exe install
- Install Gitlab runner as a service
.\gitlab-runner.exe start
- Start Gitlab runner service
Install/Setup Gitlab runner on Windows 10 with Docker
Install Hyper-V
- Log into Windows
- Open Powershell as Administrator
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All
- Install Hyper-V
- Reboot
Install WSL v2 with Linux kernel
- Log into Windows
- Open Powershell as Administrator
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
- Enable the Windows Subsystem for Linux
Enable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform -NoRestart
- Enable Virtual Machine feature
cd $ENV:TMP
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi -OutFile wsl_update_x64.msi
- Download the Linux kernel update package
msiexec.exe /i "wsl_update_x64.msi" /quiet /qn /norestart
- Install updated Linux kernel
wsl --set-default-version 2
- Set WSL 2 as default
Install Docker
- Log into Windows
- Open Powershell as Administrator
cd $ENV:TEMP
- Enter user’s temporary directory
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri https://desktop.docker.com/win/stable/Docker%20Desktop%20Installer.exe -OutFile DockerDesktopInstaller.exe
- Download Docker
.\DockerDesktopInstaller.exe install --quiet
- Install Docker
- Logout and Sign back in
- Start Docker if has no started on it’s own
& 'C:\Program Files\Docker\Docker\Docker Desktop.exe'
Install and register Gitlab-runner
mkdir 'C:\Program Files\gitlab-runner'
- Make a directory for Gitlab
cd 'C:\Program Files\gitlab-runner'
Invoke-WebRequest -Uri https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-windows-amd64.exe -OutFile gitlab-runner.exe
- Download Gitlab runner
- Open Chrome
- Browse to Gitlab homepage
- Select the “Not secure” button next to the address bar then “Certificate”
- Select. “Details” tab
- Select “Copy to file”
- Follow the instructions to export the certificate to the Desktop
- Select “Base-64 encoded X.509 (.CER)” for format
- Move the public certificate to
C:\Program Files\gitlab-runner
- Return to Powershell terminal
.\gitlab-runner.exe register --tls-ca-file .\gitlab.cer
- Register Gitlab runner
- Enter
https://gitlab.<base_domain>:8443
- Enter
<registration token>
- Accept the VM’s hostname as the Gitlab runner’s name
- Enter
windows, docker
for tags - Enter
docker-windows
for executor - Accept default Windows image
docker pull mcr.microsoft.com/windows/servercore:1809
docker pull gitlab/gitlab-runner-helper: x86_64-775dd39d-servercore1909
- Download Windows image
- In the Windows system tray right-click Docker and select “Switch to Windows Containers”
- Select “Switch” on the pop-up
.\gitlab-runner.exe install
- Install Gitlab runner as a service
.\gitlab-runner.exe start
- Start Gitlab runner service
Install/Setup Gitlab runner on Ubuntu 20.04
- SSH into Ubuntu
sudo su
apt update -y && apt install curl openssl -y
cd /tmp && curl -LJO "https://gitlab-runner-downloads.s3.amazonaws.com/latest/deb/gitlab-runner_amd64.deb"
- Download Gitlab runner
dpkg -i gitlab-runner_amd64.deb
- Install Gitlab runner
mkdir /etc/gitlab-runner/certs
- Create a directory to store the Gitlab cert
openssl s_client -connect gitlab.<base_domain>:8443 2>/dev/null </dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /etc/gitlab-runner/certs/gitlab.crt
- Grab a copy of the public cert for Gitlab
gitlab-runner register --tls-ca-file /etc/gitlab-runner/certs/gitlab.crt
- Register Gitlab runner
- Enter
https://gitlab.<base_domain>:8443
- Enter
<registration token>
- Enter
ubuntuvm
- Enter
linux, ubuntu2004
for tags - Enter
shell
for executor
rm -rd /home/gitlab-runner/*
- Delete all the dotfiles which are executed on every job run
systemctl restart gitlab-runner
systemctl enable gitlab-runner
Install/Setup Gitlab runner on macOS Big Sur
- Log into macOS
- Open terminal
sudo su
cd /tmp && curl https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-darwin-amd64 --output gitlab-runner-darwin-amd64.bin
- Download Gitlab runner
mv gitlab-runner-darwin-amd64.bin /usr/local/bin/gitlab-runner
chmod +x /usr/local/bin/gitlab-runner
- Install Gitlab runner
mkdir -p /etc/gitlab-runner/certs
cd /etc/gitlab-runner/certs
openssl s_client -connect gitlab.<base_domain>:8443 2>/dev/null </dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /etc/gitlab-runner/certs/gitlab.crt
- Grab a copy of the public cert for Gitlab
gitlab-runner register --tls-ca-file /etc/gitlab-runner/certs/gitlab.crt
- Register Gitlab runner
- Enter
https://gitlab.<base_domain>:8443
- Enter
<registration token>
- Enter
macosvm
for description - Enter
macos, macos11
for tags - Enter
shell
for executor
gitlab-runner install
gitlab-runner start
Ensure all agents have checked in
- Login in as a Gitlab admin
- Admin area > Overview > Runners
Create Gitlab pipeline
Step 1: Create example repo
- From the Gitlab user homepage
- Select “New Project”
- Select “Create blank project”
- Enter
Test-gitlab-runner
as Project name - Select “Create project”
- Enter
Step 2: Create .gitlab-ci.yml
- Select “Project overview” in the top left
- Select “New file” and select it again
- Enter
.gitlab-ci.yml
as the file name - Open a web browser to https://github.com/CptOfEvilMinions/Gitlab-Automation/blob/main/gitlab-ci-example.yml
- Copy the contents
- Paste the contents into
.gitlab-ci.yml
- Select “Commit” in bottom left
- Select “Commit” again in the bottom left
Step 3: Review pipeline jobs
Pipeline jobs
- Go to the Test-gitlab-runner repo
- CI/CD > Pipelines
- Select the latest pipeline run
test_linux_runner
test_macos_runner
test_win_runner
test_docker_runner
test_win_docker_runner
test_custom_docker_image_runner
Shoutout
A personal shout out to Valentin Despa’s Gitlab course on Udemy: GitLab CI: Pipelines, CI/CD and DevOps for Beginners. I would highly recommend taking this class to learn more about Gitlab, Gitlab runners, and creating Gitlab CI/CD pipelines in-depth.
Lessons learned
New skills/knowledge
- Learned how to use environment variables in NGINX configs per this StackOverFlow post
- Learned about how to the utility
sv
to interact with services - How to use Windows Docker containers
- Learned how to setup Gitlab runners
- Learned how to create a Gitlab CI/CD pipeline
- Learned how to push and pull images to the Docker Registry
What You’d Do Differently
- Build our Ansible playbooks for each Gitlab runner
- In an enterprise environment I would implement PKI to ensure all certificates are trusted
References
- Substitute environment variables in NGINX config from docker-compose
- Install GitLab Runner manually on GNU/Linux
- Install Hyper-V on Windows 10
- Powershell – Why is Using Invoke-WebRequest Much Slower Than a Browser Download?
- Silent installation of a MSI package
- How to Install WSL 2 on Windows 10 (Updated)
- Get started: Prep Windows for containers
- Docker Registry HTTP API V2
- Using openssl to get the certificate from a server
- Self-signed certificates or custom Certification Authorities
Many of us are tech-savy like to try out different applications according to their choices but some of them are not even unaware of how it is done or how it are the steps to install or set it up.
The information that you have shared with us about gitlab will help us in knowing it better without any problems. Thank you for sharing this with us through this article.