Continuous deployment of containerized applications using GitLab
GitLab
This tutorial describes:
- Building an application into a Docker container.
- Deploying an application from a container in a Yandex Managed Service for Kubernetes cluster via GitLab using the Yandex Cloud tools.
Each commit to GitLab is followed by:
- Running a pipeline that includes steps to build the Docker image.
- Applying a new Managed Service for Kubernetes cluster configuration specifying the application to deploy.
To set up the required infrastructure for storing source code, building the Docker image, and deploying the application, follow these steps:
If you no longer need the resources you created, delete them.
Get your cloud ready
Sign up for Yandex Cloud and create a billing account:
- Navigate to the management console
and log in to Yandex Cloud or create a new account. - On the Yandex Cloud Billing
page, make sure you have a billing account linked and it has theACTIVEorTRIAL_ACTIVEstatus. If you do not have a billing account, create one and link a cloud to it.
If you have an active billing account, you can create or select a folder for your infrastructure on the cloud page
Learn more about clouds and folders here.
Required paid resources
Infrastructure support costs include fees for the following resources:
- Disks and continuously running VMs (see Yandex Compute Cloud pricing).
- Dynamic public IP address assigned (see Yandex Virtual Private Cloud pricing).
- Storing the created Docker images (see Container Registry pricing).
- Using a Managed Service for Kubernetes master (see Managed Service for Kubernetes pricing).
Set up your infrastructure
If you do not have the Yandex Cloud CLI yet, install and initialize it.
The folder used by default is the one specified when creating the CLI profile. To change the default folder, use the yc config set folder-id <folder_ID> command. You can also specify a different folder for any command using --folder-name or --folder-id. If you access a resource by its name, the search will be limited to the default folder. If you access a resource by its ID, the search will be global, i.e., through all folders based on access permissions.
-
If you do not have a network yet, create one.
-
If you do not have any subnets yet, create them in the availability zones where the new Yandex Managed Service for Kubernetes cluster and node group will reside.
-
Create these service accounts:
- Service account for resources with the
k8s.clusters.agentandvpc.publicAdminroles for the folder to host the new Managed Service for Kubernetes cluster. This service account will be used to create Managed Service for Kubernetes cluster resources. - Service account for nodes with the container-registry.images.puller and container-registry.images.pusher roles for the folder with the Docker image registry. The Managed Service for Kubernetes nodes will use this service account to push the Docker images built in GitLab to the registry and pull them to run pods.
Tip
You can use the same service account for both operations.
- Service account for resources with the
-
Create security groups for the Managed Service for Kubernetes cluster and its node groups.
Warning
The configuration of security groups determines performance and availability of the cluster and the services and applications running in it.
-
Create a security group for the Managed Service for GitLab instance.
-
Create a Managed Service for Kubernetes cluster and a node group. When creating a Managed Service for Kubernetes cluster, specify the previously created service accounts for resources and nodes, as well as the security groups.
-
Create an authorized key for the service account with the
container-registry.images.pusherrole and save it to thekey.jsonfile:yc iam key create \ --service-account-name <service_account_name> \ --output key.jsonYou need this key to access the registry from GitLab.
-
If you do not have Terraform yet, install it.
-
Get the authentication credentials. You can add them to environment variables or specify them later in the provider configuration file.
-
Configure and initialize a provider. There is no need to create a provider configuration file manually, you can download it
. -
Place the configuration file in a separate working directory and specify the parameter values. If you did not add the authentication credentials to environment variables, specify them in the configuration file.
-
Download the k8s-and-registry-for-gitlab.tf
configuration file to your current working directory.This file describes:
-
Service account for the Managed Service for Kubernetes cluster and node group.
-
Security groups which contain rules required for the Managed Service for Kubernetes cluster and its node groups.
Warning
The configuration of security groups determines performance and availability of the cluster and the services and applications running in it.
-
Default security group and rules required for the Managed Service for GitLab instance.
-
Authorized key for the service account. You need this key to access the registry from GitLab.
-
Local
key.jsonfile with authorized key data.
-
In
k8s-and-registry-for-gitlab.tf, specify the following:- Folder ID.
- Kubernetes version for the Managed Service for Kubernetes cluster and node groups.
- Name of the Managed Service for Kubernetes cluster service account.
- Name of the Container Registry.
-
Validate your Terraform configuration files using this command:
terraform validateTerraform will display any configuration errors detected in your files.
-
Create the required infrastructure:
-
Run this command to view the planned changes:
terraform planIf you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
-
If everything looks correct, apply the changes:
-
Run this command:
terraform apply -
Confirm updating the resources.
-
Wait for the operation to complete.
-
All the required resources will be created in the specified folder. You can check resource availability and their settings in the management console
. -
Warning
For applications running in production environments, make sure to restrict access of Managed Service for Kubernetes cluster service accounts to pushing Docker images to a registry. This is required for security reasons. In that case, create a separate service account with the container-registry.images.pusher role and specify it for deploying applications.
Install additional dependencies
Install the following tools in the local environment:
jq , a JSON stream processor.- kubectl
, command-line tool. Configure it to work with the new Managed Service for Kubernetes cluster.
Create a GitLab instance
Create either a Managed Service for GitLab instance or a VM with a GitLab image in the same cloud network as the Managed Service for Kubernetes cluster.
Create a Managed Service for GitLab instance by following this guide.
Launch GitLab on a VM with a public IP address.
-
On the folder dashboard in the management console
, click Create resource and selectVirtual machine instance. -
Under Boot disk image, in the Product search field, enter
Gitlaband select a public GitLab image. -
Under Location, select the availability zone where your VM will reside. If you are not sure which one to choose, leave the default.
-
Under Computing resources, navigate to the
Customtab and specify the platform, number of vCPUs, and amount of RAM:- Platform:
Intel Ice Lake. - vCPU:
4. - Guaranteed vCPU performance:
100%. - RAM:
8 GB.
- Platform:
-
Under Network settings:
- In the Subnet field, select the network and subnet to connect your VM to. If the relevant network or subnet is missing, create it.
- In the Public IP address field, keep
Autoto assign the VM a random external IP address from the Yandex Cloud pool or select a static address from the list if you reserved one in advance.
-
Under Access, select SSH key and specify the VM access credentials:
- In the Login field, enter the username. Do not use
rootor other OS-reserved usernames. To perform operations requiring root privileges, use thesudocommand. -
In the SSH key field, select the SSH key saved in your organization user profile.
If there are no SSH keys in your profile or you want to add a new key:
-
Click Add key.
-
Enter a name for the SSH key.
-
Select one of the following:
-
Enter manually: Paste the contents of the public SSH key. You need to create an SSH key pair on your own. -
Load from file: Upload the public part of the SSH key. You need to create an SSH key pair on your own. -
Generate key: Automatically create an SSH key pair.When adding a new SSH key, an archive containing the key pair will be created and downloaded. In Linux or macOS-based operating systems, unpack the archive to the
/home/<user_name>/.sshdirectory. In Windows, unpack the archive to theC:\Users\<user_name>/.sshdirectory. You do not need additionally enter the public key in the management console.
-
-
Click Add.
The system will add the SSH key to your organization user profile. If the organization has disabled the ability for users to add SSH keys to their profiles, the added public SSH key will only be saved in the user profile inside the newly created resource.
-
- In the Login field, enter the username. Do not use
-
Under General information, specify the VM name:
ci-tutorial-gitlab. -
Click Create VM.
It may take a few minutes to create your VM. When the VM status changes to RUNNING and GitLab starts, configure its settings.
Configure GitLab
To configure GitLab and get ready for continuous integration (CI), create a new project and enter the CI authentication data:
-
Log in to the Managed Service for GitLab instance web UI.
-
Click Create a project.
-
Click Create blank project.
-
Fill out the fields as follows:
- Project name:
gitlab-test. - Project URL: Select the admin user in the field next to the Managed Service for GitLab instance FQDN.
Leave the other fields unchanged.
- Project name:
-
Click Create project.
-
On the Yandex Compute Cloud page, select the created VM and copy its public IP.
-
Connect to the VM over SSH.
-
Get the GitLab administrator password with the following VM command:
sudo cat /etc/gitlab/initial_root_password -
Copy the password without spaces from the
Passwordline to the clipboard or a separate file. -
In your browser, open
http://<VM_public_IP_address>. This will take you to the GitLab web UI. -
Log in as the administrator:
- Username or email:
root. - Password: Password you copied in the previous step.
If you are unable to log in, reset the administrator password
. - Username or email:
-
Log in as the administrator with the new password.
-
Select Create a project.
-
Specify the project name:
gitlab-test. -
Click Create project.
Create a test application
Create a test application that can be deployed in a Yandex Managed Service for Kubernetes cluster:
- Add a
Dockerfileto your project:-
Log in to GitLab.
-
Open the GitLab project.
-
Click
in the repository navigation bar and select New file from the drop-down menu. -
Name the file
Dockerfileand add the following code to it:FROM alpine:3.10 CMD echo "Hello" -
Add a comment in the Commit message field:
Dockerfile for test application. -
Click Commit changes.
-
- Add a manifest for creating Managed Service for Kubernetes cluster resources to your project:
-
Open the GitLab project.
-
Click
in the repository navigation bar and select New file from the drop-down menu. -
Name your file
k8s.yaml:k8s.yaml
apiVersion: v1 kind: Namespace metadata: name: hello-world --- apiVersion: apps/v1 kind: Deployment metadata: name: hello-world-deployment namespace: hello-world spec: replicas: 1 selector: matchLabels: app: hello template: metadata: namespace: hello-world labels: app: hello spec: containers: - name: hello-world image: __VERSION__ imagePullPolicy: Always -
Add a comment in the Commit message field:
Docker image deployment config. -
Click Commit changes.
-
Create a GitLab Runner
To run build tasks in your Yandex Managed Service for Kubernetes cluster, create a GitLab Runner
Once it is installed, you can run automated builds within your Managed Service for Kubernetes cluster.
For more information about installing and running GitLab Runner, see this GitLab article
Set up Kubernetes authentication in GitLab
You can set up authentication in GitLab using a Kubernetes service account token or the GitLab Agent application:
Note
The Kubernetes service account is not the same as the Yandex Identity and Access Management service account.
To get a Kubernetes service account token:
- Create a service account.
- Get a service account token.
- Save the token, as you will need it in the next steps.
To connect your Yandex Managed Service for Kubernetes cluster to GitLab, create a GitLab Agent
Once it is installed, you can connect your Managed Service for Kubernetes cluster to a GitLab instance.
For more information about installing and running GitLab Agent, see this GitLab article
Configure the CI pipeline
-
Create GitLab environment variables
:-
In GitLab, navigate to Settings in the left-hand panel and select CI/CD from the pop-up list.
-
Click Expand next to Variables.
-
Add the following environment variables depending on the Kubernetes authentication method in GitLab:
Service account tokenGitLab Agent-
KUBE_URL: Managed Service for Kubernetes master address. You can get it using the following command:yc managed-kubernetes cluster get <cluster_ID_or_name> --format=json \ | jq -r .master.endpoints.external_v4_endpoint -
KUBE_TOKEN: Token that GitLab will use to apply the configuration. Use the token you got earlier.
CI_REGISTRY: Address of the previously created registry incr.yandex/<registry_ID>format.CI_REGISTRY_KEY: Key that GitLab will use to access the registry. Copy the contents of the previously obtainedkey.jsonstatic key file to access the registry.
To add a variable:
- Click Add variable.
- In the window that opens, specify a variable name in the Key field and its value in the Value field.
- Click Add variable.
-
-
-
Create a CI pipeline configuration file:
-
Open the
gitlab-testproject. -
Click
in the repository navigation bar and select New file from the drop-down menu. -
Name your file
.gitlab-ci.yml. Add steps to build and push the Docker image and update the application configuration in the Managed Service for Kubernetes cluster. The file structure depends on the Kubernetes authentication method in GitLab:Service account tokenGitLab Agent-
To build a container via
kanikowithout using the GitLab Runner privileged mode:.gitlab-ci.yml
stages: - build - deploy build: stage: build image: name: gcr.io/kaniko-project/executor:debug entrypoint: [""] script: - mkdir -p /kaniko/.docker - echo "{\"auths\":{\"${CI_REGISTRY}\":{\"auth\":\"$(echo -n "json_key:${CI_REGISTRY_KEY}" | base64 | tr -d '\n' )\"}}}" > /kaniko/.docker/config.json - >- /kaniko/executor --context "${CI_PROJECT_DIR}" --dockerfile "${CI_PROJECT_DIR}/Dockerfile" --destination "${CI_REGISTRY}/${CI_PROJECT_PATH}:${CI_COMMIT_SHORT_SHA}" deploy: image: gcr.io/cloud-builders/kubectl:latest stage: deploy script: - kubectl config set-cluster k8s --server="$KUBE_URL" --insecure-skip-tls-verify=true - kubectl config set-credentials admin --token="$KUBE_TOKEN" - kubectl config set-context default --cluster=k8s --user=admin - kubectl config use-context default - sed -i "s,__VERSION__,${CI_REGISTRY}/${CI_PROJECT_PATH}:${CI_COMMIT_SHORT_SHA}," k8s.yaml - kubectl apply -f k8s.yaml -
To build a container via
docker:dindusing the GitLab Runner privileged mode:.gitlab-ci.yml
stages: - build - deploy image: docker:20.10.16 variables: DOCKER_HOST: tcp://docker:2376 DOCKER_TLS_CERTDIR: "/certs" DOCKER_TLS_VERIFY: 1 DOCKER_CERT_PATH: "$DOCKER_TLS_CERTDIR/client" DOCKER_DRIVER: overlay2 services: - docker:20.10.16-dind before_script: - for try in {1..10}; do sleep 0.5; docker info && break ; done build: stage: build script: - echo "${CI_REGISTRY_KEY}" | docker login ${CI_REGISTRY} -u json_key --password-stdin - >- docker build "${CI_PROJECT_DIR}" --file "${CI_PROJECT_DIR}/Dockerfile" --tag "${CI_REGISTRY}/${CI_PROJECT_PATH}:${CI_COMMIT_SHORT_SHA}" - docker push "${CI_REGISTRY}/${CI_PROJECT_PATH}:${CI_COMMIT_SHORT_SHA}" deploy: image: gcr.io/cloud-builders/kubectl:latest stage: deploy script: - kubectl config set-cluster k8s --server="$KUBE_URL" --insecure-skip-tls-verify=true - kubectl config set-credentials admin --token="$KUBE_TOKEN" - kubectl config set-context default --cluster=k8s --user=admin - kubectl config use-context default - sed -i "s,__VERSION__,${CI_REGISTRY}/${CI_PROJECT_PATH}:${CI_COMMIT_SHORT_SHA}," k8s.yaml - kubectl apply -f k8s.yaml
-
To build a container via
kanikowithout using the GitLab Runner privileged mode:.gitlab-ci.yml
stages: - build - deploy build: stage: build image: name: gcr.io/kaniko-project/executor:debug entrypoint: [""] script: - mkdir -p /kaniko/.docker - echo "{\"auths\":{\"${CI_REGISTRY}\":{\"auth\":\"$(echo -n "json_key:${CI_REGISTRY_KEY}" | base64 | tr -d '\n' )\"}}}" > /kaniko/.docker/config.json - >- /kaniko/executor \ --context "${CI_PROJECT_DIR}" \ --dockerfile "${CI_PROJECT_DIR}/Dockerfile" \ --destination "${CI_REGISTRY}/${CI_PROJECT_PATH}:${CI_COMMIT_SHORT_SHA}" deploy: image: bitnamilegacy/kubectl:latest stage: deploy script: - kubectl config use-context ${CI_PROJECT_PATH}:<GitLab_agent_name> - cat k8s.yaml | sed -e "s,__VERSION__,${CI_REGISTRY}/${CI_PROJECT_PATH}:${CI_COMMIT_SHORT_SHA}," | kubectl apply -f - -
To build a container via
docker:dindusing the GitLab Runner privileged mode:.gitlab-ci.yml
stages: - build - deploy image: docker:20.10.16 variables: DOCKER_HOST: tcp://docker:2376 DOCKER_TLS_CERTDIR: "/certs" DOCKER_TLS_VERIFY: 1 DOCKER_CERT_PATH: "$DOCKER_TLS_CERTDIR/client" DOCKER_DRIVER: overlay2 services: - docker:20.10.16-dind before_script: - for try in {1..10}; do sleep 0.5; docker info && break ; done build: stage: build script: - echo "${CI_REGISTRY_KEY}" | docker login ${CI_REGISTRY} -u json_key --password-stdin - >- docker build "${CI_PROJECT_DIR}" --file "${CI_PROJECT_DIR}/Dockerfile" --tag "${CI_REGISTRY}/${CI_PROJECT_PATH}:${CI_COMMIT_SHORT_SHA}" - docker push "${CI_REGISTRY}/${CI_PROJECT_PATH}:${CI_COMMIT_SHORT_SHA}" deploy: image: name: bitnamilegacy/kubectl:latest entrypoint: [""] stage: deploy script: - kubectl config use-context ${CI_PROJECT_PATH}:<GitLab_agent_name> - cat k8s.yaml | sed -e "s,__VERSION__,${CI_REGISTRY}/${CI_PROJECT_PATH}:${CI_COMMIT_SHORT_SHA}," | kubectl apply -f -
Replace
<GitLab_agent_name>with the name of the agent in Managed Service for GitLab. -
-
Add a comment in the Commit message field:
CI scripts. -
Click Commit changes.
The
.gitlab-ci.ymlfile describes the following two steps of the project build process:- Building a Docker image using
Dockerfileand pushing the image to Container Registry. - Setting up an environment to work with Kubernetes and applying the
k8s.yamlconfiguration to the Managed Service for Kubernetes cluster. This way, the application is deployed to the previously created Managed Service for Kubernetes cluster.
-
Check the result
-
After you save the
.gitlab-ci.ymlconfiguration file, the build pipeline will start. To check its results, select Build on the left-hand panel in thegitlab-testproject, then select Pipelines from the drop-down menu, and wait for both build stages to complete successfully. -
To check how the application is running in your Managed Service for Kubernetes cluster, view its container logs:
kubectl logs deployment/hello-world-deployment -n hello-worldResult:
Hello
Delete the resources you created
Some resources are not free of charge. Delete the resources you no longer need to avoid paying for them:
-
Delete the Managed Service for Kubernetes cluster and Container Registry:
ManuallyTerraform-
In the terminal window, go to the directory containing the infrastructure plan.
Warning
Make sure the directory has no Terraform manifests with the resources you want to keep. Terraform deletes all resources that were created using the manifests in the current directory.
-
Delete resources:
-
Run this command:
terraform destroy -
Confirm deleting the resources and wait for the operation to complete.
All the resources described in the Terraform manifests will be deleted.
-
-
-
Delete the created GitLab VM or Managed Service for GitLab instance.