[Yandex Cloud documentation](../../index.md) > [Yandex Container Registry](../index.md) > [Tutorials](index.md) > Continuous deployment of containerized applications using GitLab

# Continuous deployment of containerized applications using GitLab

[GitLab](https://about.gitlab.com/) is a tool for continuous integration (CI).

This tutorial describes:
* Building an application into a Docker container.
* Deploying an application from a container in a [Yandex Managed Service for Kubernetes cluster](../../managed-kubernetes/concepts/index.md#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](../concepts/docker-image.md).
* 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:
1. [Get your cloud ready](#before-you-begin).

   1. [Review the list of required paid resources](#paid-resources).

1. [Set up your infrastructure](#deploy-infrastructure).
1. [Create a GitLab instance](#create-gitlab).
1. [Configure GitLab](#configure-gitlab).
1. [Create a test application](#app-create).
1. [Create a GitLab Runner](#runners).
1. [Set up Kubernetes authentication in GitLab](#gitlab-authentication).
1. [Configure the CI pipeline](#ci).
1. [Check the result](#check-result).

If you no longer need the resources you created, [delete them](#clear-out).

## Get your cloud ready {#before-you-begin}

Sign up for Yandex Cloud and create a [billing account](../../billing/concepts/billing-account.md):
1. Navigate to the [management console](https://console.yandex.cloud) and log in to Yandex Cloud or create a new account.
1. On the **[Yandex Cloud Billing](https://center.yandex.cloud/billing/accounts)** page, make sure you have a billing account linked and it has the `ACTIVE` or `TRIAL_ACTIVE` [status](../../billing/concepts/billing-account-statuses.md). If you do not have a billing account, [create one](../../billing/quickstart/index.md) and [link](../../billing/operations/pin-cloud.md) a cloud to it.

If you have an active billing account, you can create or select a [folder](../../resource-manager/concepts/resources-hierarchy.md#folder) for your infrastructure on the [cloud page](https://console.yandex.cloud/cloud).

[Learn more about clouds and folders here](../../resource-manager/concepts/resources-hierarchy.md).

### Required paid resources {#paid-resources}

Infrastructure support costs include fees for the following resources:
* [Disks](../../compute/concepts/disk.md) and continuously running [VMs](../../compute/concepts/vm.md) (see [Yandex Compute Cloud pricing](../../compute/pricing.md)).
* Dynamic [public IP address](../../vpc/concepts/ips.md) assigned (see [Yandex Virtual Private Cloud pricing](../../vpc/pricing.md#prices-public-ip)).
* Storing the created Docker images (see [Container Registry pricing](../pricing.md)).
* Using a [Managed Service for Kubernetes master](../../managed-kubernetes/concepts/index.md#master) (see [Managed Service for Kubernetes pricing](../../managed-kubernetes/pricing.md)).

### Set up your infrastructure {#deploy-infrastructure}

{% list tabs group=instructions %}

- Manually {#manual}

  If you do not have the Yandex Cloud CLI yet, [install and initialize it](../../cli/quickstart.md#install).

  The folder used by default is the one specified when [creating](../../cli/operations/profile/profile-create.md) 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.

  1. If you do not have a [network](../../vpc/concepts/network.md#network) yet, [create one](../../vpc/operations/network-create.md).
  1. If you do not have any [subnets](../../vpc/concepts/network.md#subnet) yet, [create them](../../vpc/operations/subnet-create.md) in the [availability zones](../../overview/concepts/geo-scope.md) where the new [Yandex Managed Service for Kubernetes cluster](../../managed-kubernetes/concepts/index.md#kubernetes-cluster) and [node group](../../managed-kubernetes/concepts/index.md#node-group) will reside.
  1. [Create these service accounts](../../iam/operations/sa/create.md):
     * Service account for resources with the `k8s.clusters.agent` and `vpc.publicAdmin` [roles](../../iam/concepts/access-control/roles.md) for the [folder](../../resource-manager/concepts/resources-hierarchy.md#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](../security/index.md#container-registry-images-puller) and [container-registry.images.pusher](../security/index.md#container-registry-images-pusher) roles for the folder with the [Docker image](../concepts/docker-image.md) [registry](../concepts/registry.md). 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](../../managed-kubernetes/concepts/index.md#pod).

     {% note tip %}

     You can use the same [service account](../../iam/concepts/users/service-accounts.md) for both operations.

     {% endnote %}

  1. [Create security groups](../../managed-kubernetes/operations/connect/security-groups.md) for the Managed Service for Kubernetes cluster and its node groups.

        {% note warning %}
        
        The configuration of security groups determines performance and availability of the cluster and the services and applications running in it.
        
        {% endnote %}

  1. [Create a security group](../../managed-gitlab/operations/configure-security-group.md) for the [Managed Service for GitLab instance](../../managed-gitlab/concepts/index.md#instance).

  1. [Create a Managed Service for Kubernetes cluster](../../managed-kubernetes/operations/kubernetes-cluster/kubernetes-cluster-create.md#kubernetes-cluster-create) and a [node group](../../managed-kubernetes/operations/node-group/node-group-create.md). When creating a Managed Service for Kubernetes cluster, specify the previously created service accounts for resources and nodes, as well as the security groups.

  1. [Create a Yandex Container Registry](../operations/registry/registry-create.md).
  1. [Create an authorized key](../../iam/operations/authentication/manage-authorized-keys.md#create-authorized-key) for the service account with the `container-registry.images.pusher` role and save it to the `key.json` file:

     ```bash
     yc iam key create \
       --service-account-name <service_account_name> \
       --output key.json
     ```

     You need this key to access the registry from GitLab.

- Terraform {#tf}

  1. If you do not have Terraform yet, [install it](../../tutorials/infrastructure-management/terraform-quickstart.md#install-terraform).
  1. [Get the authentication credentials](../../tutorials/infrastructure-management/terraform-quickstart.md#get-credentials). You can add them to environment variables or specify them later in the provider configuration file.
  1. [Configure and initialize a provider](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). There is no need to create a provider configuration file manually, you can [download it](https://github.com/yandex-cloud-examples/yc-terraform-provider-settings/blob/main/provider.tf).
  1. Place the configuration file in a separate working directory and [specify the parameter values](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). If you did not add the authentication credentials to environment variables, specify them in the configuration file.

  1. Download the [k8s-and-registry-for-gitlab.tf](https://github.com/yandex-cloud-examples/yc-mk8s-cr-gitlab/blob/main/k8s-and-registry-for-gitlab.tf) configuration file to your current working directory.

     This file describes:
     * [Network](../../vpc/concepts/network.md#network).
     * [Subnet](../../vpc/concepts/network.md#subnet).
     * [Managed Service for Kubernetes cluster](../../managed-kubernetes/concepts/index.md#kubernetes-cluster).
     * [Service account](../../iam/concepts/users/service-accounts.md) for the Managed Service for Kubernetes cluster and [node group](../../managed-kubernetes/concepts/index.md#node-group).
     * [Security groups](../../vpc/concepts/security-groups.md) which contain [rules](../../managed-kubernetes/operations/connect/security-groups.md) required for the Managed Service for Kubernetes cluster and its node groups.

        {% note warning %}
        
        The configuration of security groups determines performance and availability of the cluster and the services and applications running in it.
        
        {% endnote %}

     * [Default security group](../../vpc/concepts/security-groups.md#default-security-group) and rules required for the [Managed Service for GitLab instance](../../managed-gitlab/concepts/index.md#instance).
     * [Registry](../concepts/registry.md) in [Yandex Container Registry](../index.md).
     * [Authorized key](../../iam/concepts/authorization/key.md) for the service account. You need this key to access the registry from GitLab.
     * Local `key.json` file with authorized key data.
  1. In `k8s-and-registry-for-gitlab.tf`, specify the following:
     * [Folder ID](../../resource-manager/operations/folder/get-id.md).
     * [Kubernetes version](../../managed-kubernetes/concepts/release-channels-and-updates.md) 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.
  1. Make sure the Terraform configuration files are correct using this command:

     ```bash
     terraform validate
     ```

     Terraform will display any configuration errors detected in your files.
  1. Create the required infrastructure:

     1. Run this command to view the planned changes:
     
        ```bash
        terraform plan
        ```
     
        If 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.
     
     1. If everything looks correct, apply the changes:
        1. Run this command:
     
           ```bash
           terraform apply
           ```
     
        1. Confirm updating the resources.
        1. 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](https://console.yandex.cloud).

{% endlist %}

{% note 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.

{% endnote %}

### Install additional dependencies {#prepare}

Install the following tools in the local environment:
* [`jq`](https://stedolan.github.io/jq/), a JSON stream processor.
* [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl), command-line tool. [Configure it to work with the new Managed Service for Kubernetes cluster](../../managed-kubernetes/operations/connect/index.md#kubectl-connect).

## Create a GitLab instance {#create-gitlab}

Create either a [Managed Service for GitLab instance](../../managed-gitlab/concepts/index.md#instance) or a [VM](../../compute/concepts/vm.md) with a [GitLab image](../../compute/concepts/image.md) in the same [cloud network](../../vpc/concepts/network.md#network) as the [Managed Service for Kubernetes cluster](../../managed-kubernetes/concepts/index.md#kubernetes-cluster).

{% list tabs group=gl_installation %}

- Managed Service for GitLab instance {#instance-mgl}

  Create a Managed Service for GitLab instance by following [this guide](../../managed-gitlab/quickstart.md#instance-create).

- VM with a GitLab image {#gl-image-vm}

  Launch GitLab on a VM with a [public IP address](../../vpc/concepts/address.md#public-addresses).

  1. On the [folder dashboard](../../resource-manager/concepts/resources-hierarchy.md#folder) in the [management console](https://console.yandex.cloud), click **Create resource** and select `Virtual machine instance`.
  1. Under **Boot disk image**, in the **Product search** field, enter `Gitlab` and select a public [GitLab](https://yandex.cloud/en/marketplace/products/yc/gitlab) image.
  1. Under **Location**, select the [availability zone](../../overview/concepts/geo-scope.md) where your VM will reside. If you are not sure which one to choose, leave the default.
  1. Under **Computing resources**, navigate to the `Custom` tab and specify the [platform](../../compute/concepts/vm-platforms.md), number of vCPUs, and amount of RAM:
  
      * **Platform**: `Intel Ice Lake`.
      * **vCPU**: `4`.
      * **Guaranteed vCPU performance**: `100%`.
      * **RAM**: `8 GB`.
  
  1. Under **Network settings**:
      
      * In the **Subnet** field, select the network and subnet to connect your VM to. If the relevant [network](../../vpc/concepts/network.md#network) or [subnet](../../vpc/concepts/network.md#subnet) is missing, [create it](../../vpc/operations/subnet-create.md).
      * In the **Public IP address** field, keep `Auto` to 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.
  
  1. Under **Access**, select **SSH key** and specify the VM access credentials:
  
      * In the **Login** field, enter the username. Do not use `root` or other OS-reserved usernames. To perform operations requiring root privileges, use the `sudo` command.
      * In the **SSH key** field, select the SSH key saved in your [organization user](../../organization/concepts/membership.md) profile.
        
        If there are no SSH keys in your profile or you want to add a new key:
        
        1. Click **Add key**.
        1. Enter a name for the SSH key.
        1. Select one of the following:
        
            * `Enter manually`: Paste the contents of the public SSH key. You need to [create](../../compute/operations/vm-connect/ssh.md#creating-ssh-keys) 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>/.ssh` directory. In Windows, unpack the archive to the `C:\Users\<user_name>/.ssh` directory. You do not need additionally enter the public key in the management console.
        
        1. Click **Add**.
        
        The system will add the SSH key to your organization user profile. If the organization has [disabled](../../organization/operations/os-login-access.md) 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.
  
  1. Under **General information**, specify the VM name: `ci-tutorial-gitlab`.
  1. 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.

{% endlist %}

## Configure GitLab {#configure-gitlab}

To configure GitLab and get ready for continuous integration (CI), create a new project and enter the CI authentication data:

{% list tabs group=gl_installation %}

- Managed Service for GitLab instance {#instance-mgl}

  1. Log in to the [Managed Service for GitLab instance](../../managed-gitlab/concepts/index.md#instance) web UI.
  1. Click **Create a project**.
  1. Click **Create blank project**.
  1. 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.
  1. Click **Create project**.

- VM with a GitLab image {#gl-image-vm}

  1. On the Yandex Compute Cloud page, select the created [VM](../../compute/concepts/vm.md) and copy its [public IP](../../vpc/concepts/address.md#public-addresses).
  1. [Connect](../../compute/operations/vm-connect/ssh.md) to the VM over SSH.
  1. Get the GitLab administrator password with the following VM command:

     ```bash
     sudo cat /etc/gitlab/initial_root_password
     ```

  1. Copy the password without spaces from the `Password` line to the clipboard or a separate file.
  1. In your browser, open `http://<VM_public_IP_address>`. This will take you to the GitLab web UI.
  1. 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](https://docs.gitlab.com/security/reset_user_password/#reset-your-root-password).
  1. [Change the administrator password](https://docs.gitlab.com/user/profile/user_passwords/#change-your-password).
  1. Log in as the administrator with the new password.
  1. Select **Create a project**.
  1. Specify the project name: `gitlab-test`.
  1. Click **Create project**.

{% endlist %}

## Create a test application {#app-create}

Create a test application that can be deployed in a [Yandex Managed Service for Kubernetes cluster](../../managed-kubernetes/concepts/index.md#kubernetes-cluster):
1. Add a `Dockerfile` to your project:
   1. Log in to GitLab.
   1. Open the GitLab project.
   1. Click ![image](../../_assets/console-icons/plus.svg) in the repository navigation bar and select **New file** from the drop-down menu.
   1. Name the file `Dockerfile` and add the following code to it:

      ```Dockerfile
      FROM alpine:3.10
      CMD echo "Hello"
      ```

   1. Add a comment in the **Commit message** field: `Dockerfile for test application`.
   1. Click **Commit changes**.
1. Add a manifest for creating Managed Service for Kubernetes cluster resources to your project:
   1. Open the GitLab project.
   1. Click ![image](../../_assets/console-icons/plus.svg) in the repository navigation bar and select **New file** from the drop-down menu.
   1. Name your file `k8s.yaml`:

      {% cut "k8s.yaml" %}

      ```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
      ```

      {% endcut %}

   1. Add a comment in the **Commit message** field: `Docker image deployment config`.
   1. Click **Commit changes**.

## Create a GitLab Runner {#runners}

To run build tasks in your [Yandex Managed Service for Kubernetes cluster](../../managed-kubernetes/concepts/index.md#kubernetes-cluster), create a [GitLab Runner](https://docs.gitlab.com/runner/install/kubernetes/).To do this, install GitLab Runner by following [this guide](../../managed-kubernetes/operations/applications/gitlab-runner.md).

Once it is installed, you can run automated builds within your [Managed Service for Kubernetes cluster](../../managed-kubernetes/concepts/index.md#kubernetes-cluster).

For more information about installing and running GitLab Runner, see [this GitLab article](https://docs.gitlab.com/runner/install/).

## Set up Kubernetes authentication in GitLab {#gitlab-authentication}

You can set up authentication in GitLab using a Kubernetes service account token or the [GitLab Agent](https://yandex.cloud/en/marketplace/products/yc/gitlab-agent) application:

{% list tabs group=gl_auth %}

- Service account token {#token}

   ### Get a Kubernetes service account token to authenticate with GitLab {#k8s-get-token}
   
   {% note info %}
   
   The [Kubernetes service account](../../managed-kubernetes/concepts/index.md#service-accounts) is not the same as the [Yandex Identity and Access Management service account](../../iam/concepts/users/service-accounts.md).
   
   {% endnote %}
   
   To get a Kubernetes service account token:
   1. [Create a service account](../../managed-kubernetes/operations/connect/create-static-conf.md#create-sa).
   1. [Get a service account token](../../managed-kubernetes/operations/connect/create-static-conf.md#prepare-token).
   1. Save the token, as you will need it in the next steps.

- GitLab Agent {#gla}

   ## Create a GitLab Agent {#agent}
   
   To connect your [Yandex Managed Service for Kubernetes cluster](../../managed-kubernetes/concepts/index.md#kubernetes-cluster) to GitLab, create a [GitLab Agent](https://docs.gitlab.com/ee/user/clusters/agent/). To do this, install GitLab Agent by following [this guide](../../managed-kubernetes/operations/applications/gitlab-agent.md).
   
   Once it is installed, you can connect your [Managed Service for Kubernetes cluster](../../managed-kubernetes/concepts/index.md#kubernetes-cluster) to a [GitLab instance](../../managed-gitlab/concepts/index.md#instance).
   
   For more information about installing and running GitLab Agent, see [this GitLab article](https://docs.gitlab.com/ee/user/clusters/agent/).

{% endlist %}

## Configure the CI pipeline {#ci}

1. Create [GitLab environment variables](https://docs.gitlab.com/ee/ci/variables/):
   1. In GitLab, navigate to **Settings** in the left-hand panel and select **CI/CD** from the pop-up list.
   1. Click **Expand** next to **Variables**.
   1. Add the following environment variables depending on the Kubernetes authentication method in GitLab:

      {% list tabs group=gl_auth %}

      - Service account token {#token}

        * `KUBE_URL`: Managed Service for Kubernetes master address. You can get it using the following command:

          ```bash
          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.

      - GitLab Agent {#gla}

      {% endlist %}

      * `CI_REGISTRY`: Address of the previously created registry in `cr.yandex/<registry_ID>` format.
      * `CI_REGISTRY_KEY`: Key that GitLab will use to access the registry. Copy the contents of the previously obtained `key.json` static 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**.
1. Create a CI pipeline configuration file:
   1. Open the `gitlab-test` project.
   1. Click ![image](../../_assets/console-icons/plus.svg) in the repository navigation bar and select **New file** from the drop-down menu.
   1. 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:

      {% list tabs group=gl_auth %}

      - Service account token {#token}

        * To build a container via `kaniko` without using the GitLab Runner privileged mode:

          {% cut ".gitlab-ci.yml" %}

          ```yaml
          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
          ```

          {% endcut %}

        * To build a container via `docker:dind` using the GitLab Runner privileged mode:

          {% cut ".gitlab-ci.yml" %}

          ```yaml
          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
          ```

          {% endcut %}

      - GitLab Agent {#gla}

        * To build a container via `kaniko` without using the GitLab Runner privileged mode:

          {% cut ".gitlab-ci.yml" %}

          ```yaml
          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 -
          ```

          {% endcut %}

        * To build a container via `docker:dind` using the GitLab Runner privileged mode:

          {% cut ".gitlab-ci.yml" %}

          ```yaml
          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 -
          ```

          {% endcut %}

        Replace `<GitLab_agent_name>` with the name of the agent in Managed Service for GitLab.

      {% endlist %}

   1. Add a comment in the **Commit message** field: `CI scripts`.
   1. Click **Commit changes**.

   The `.gitlab-ci.yml` file describes the following two steps of the project build process:
   * Building a Docker image using `Dockerfile` and pushing the image to Container Registry.
   * Setting up an environment to work with Kubernetes and applying the `k8s.yaml` configuration 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 {#check-result}

1. After you save the `.gitlab-ci.yml` configuration file, the build pipeline will start. To check its results, select **Build** on the left-hand panel in the `gitlab-test` project, then select **Pipelines** from the drop-down menu, and wait for both build stages to complete successfully.
1. To check how the application is running in your Managed Service for Kubernetes cluster, view its container logs:

   ```bash
   kubectl logs deployment/hello-world-deployment -n hello-world
   ```

   Result:

   ```text
   Hello
   ```

## Delete the resources you created {#clear-out}

Some resources are not free of charge. Delete the resources you no longer need to avoid paying for them:
1. [Delete the created Docker images](../operations/docker-image/docker-image-delete.md).
1. Delete the Managed Service for Kubernetes cluster and Container Registry:

   {% list tabs group=instructions %}

   - Manually {#manual}

     1. [Delete the Managed Service for Kubernetes cluster](../../managed-kubernetes/operations/kubernetes-cluster/kubernetes-cluster-delete.md).
     1. [Delete the Container Registry](../operations/registry/registry-delete.md).
     1. [Delete the created subnets](../../vpc/operations/subnet-delete.md) and [networks](../../vpc/operations/network-delete.md).
     1. [Delete the created service accounts](../../iam/operations/sa/delete.md).

   - Terraform {#tf}

     1. In the terminal window, go to the directory containing the infrastructure plan.
     
         {% note 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.
     
         {% endnote %}
     
     1. Delete resources:
     
         1. Run this command:
     
             ```bash
             terraform destroy
             ```
     
         1. Confirm deleting the resources and wait for the operation to complete.
     
         All the resources described in the Terraform manifests will be deleted.

   {% endlist %}

1. [Delete the created GitLab VM](../../compute/operations/vm-control/vm-delete.md) or Managed Service for GitLab instance.

## See also {#see-also}

* [Creating test VMs using GitLab CI](../../tutorials/testing/ci-for-snapshots.md).