Gitlab CI/CD
Gitlab CI is one of the easiest continous Integration and Deployment tool to start when looking for devops activities. Gitlab has a concept of runner which is essentially an agent installed on a machine with various capabilites to perform certain tasks. These tasks include compiling the code, building docker images, deploying web apps to production servers. There are various types of runners based on how they perform certain tasks. We are particularly interested in docker runner.
To use a docker runner we first install a gitlab runner agent on a machine where we want perform these activities. Upon selecting the type of runner we specify docker. To use docker as a type of runner we must have docker installed in the machine on which we are installing gitlab-runner. We can configure this runner as a group runner or a shared runner. A group runner gets automatically assigned the tasks when CI/CD operations are initiated on project inside a group in gitlab. We have a group fronted where there are some projects based on various fronted technologies. Once automation pipeline get triggered in any of the project it is assigned to the runner by default.
The default CI/CD file for Gitlab is .gitlab-ci.yaml
. It lives in the top level of the project and contains all tasks related to automation ing gitlab.
stages:
- build
- deploy
test-job:
stage: build
image: docker
services:
- docker:dind
before_script:
- echo ${REGISTRY_PASSWORD} | docker login ${CI_REGISTRY} -u ${REGISTRY_USER} --password-stdin
script:
- docker build . -t ${CI_REGISTRY}/demoapp:${CI_COMMIT_SHORT_SHA}
- docker push ${CI_REGISTRY}/demoapp:${CI_COMMIT_SHORT_SHA}
tags: [hardware]
deploy-job:
stage: deploy
tags: [hardware]
before_script:
- chmod 400 ${SSH_KEY}
script:
- ssh -o StrictHostKeyChecking=no -i ${SSH_KEY} ubuntu@192.168.20.219 -p 2222 "
docker rm -f demoapp_prod 2>/dev/null || true &&
echo ${REGISTRY_PASSWORD} | docker login ${CI_REGISTRY} -u ${REGISTRY_USER} --password-stdin &&
docker run --rm --name demoapp_prod -d -p 3030:3030 ${CI_REGISTRY}/demoapp:${CI_COMMIT_SHORT_SHA}"
only:
- main
environment:
name: production
url: http://192.168.20.219:3030
The variables ${REGISTRY_USER}
,${REGISTRY_PASSWORD}
,${CI_REGISTRY}
, ${CI_COMMIT_SHA_SHORT}
, ${SSH_KEY}
supplied from gitlab to the docker based runner targeted using tags: [hardware]
. Here are two stages on the automation pipeline build
and deploy
which as the name suggests. The build
stage builds the docker container for our application and pushes the code to private docker registry. The deploy stage deploys new docker container on the production instance. Although other stages like testing and scanning can be adding. This can be the basic git CI/CD pipeline.