gitlab.com/jfprevost/gitlab-runner-notlscheck@v11.11.4+incompatible/docs/executors/kubernetes.md (about)

     1  # The Kubernetes executor
     2  
     3  GitLab Runner can use Kubernetes to run builds on a kubernetes cluster. This is
     4  possible with the use of the **Kubernetes** executor.
     5  
     6  The **Kubernetes** executor, when used with GitLab CI, connects to the Kubernetes
     7  API in the cluster creating a Pod for each GitLab CI Job. This Pod is made
     8  up of, at the very least, a build container and an additional container for each
     9  `service` defined by the GitLab CI yaml. The names for these containers
    10  are as follows:
    11  
    12  - The build container is `build`
    13  - The services containers are `svc-X` where `X` is `[0-9]+`
    14  
    15  Note that when services and containers are running in the same Kubernetes
    16  pod, they are all sharing the same localhost address. The following restrictions
    17  are then applicable:
    18  
    19  - The services are *not* accessible via their DNS name, you need to use localhost
    20    instead.
    21  - You cannot use several services using the same port (e.g., you cannot have two
    22    `mysql` services at the same time).
    23  
    24  ## Workflow
    25  
    26  The Kubernetes executor divides the build into multiple steps:
    27  
    28  1. **Prepare**: Create the Pod against the Kubernetes Cluster.
    29  	This creates the containers required for the build and services to run.
    30  1. **Pre-build**: Clone, restore cache and download artifacts from previous
    31     stages. This is run on a special container as part of the Pod.
    32  1. **Build**: User build.
    33  1. **Post-build**: Create cache, upload artifacts to GitLab. This also uses
    34     the special container as part of the Pod.
    35  
    36  ## Connecting to the Kubernetes API
    37  
    38  The following options are provided, which allow you to connect to the Kubernetes API:
    39  
    40  - `host`: Optional Kubernetes apiserver host URL (auto-discovery attempted if not specified)
    41  - `cert_file`: Optional Kubernetes apiserver user auth certificate
    42  - `key_file`: Optional Kubernetes apiserver user auth private key
    43  - `ca_file`: Optional Kubernetes apiserver ca certificate
    44  
    45  The user account provided must have permission to create, list and attach to Pods in
    46  the specified namespace in order to function.
    47  
    48  If you are running the GitLab CI Runner within the Kubernetes cluster you can omit
    49  all of the above fields to have the Runner auto-discovery the Kubernetes API. This
    50  is the recommended approach.
    51  
    52  If you are running it externally to the Cluster then you will need to set each
    53  of these keywords and make sure that the Runner has access to the Kubernetes API
    54  on the cluster.
    55  
    56  ## The keywords
    57  
    58  The following keywords help to define the behaviour of the Runner within Kubernetes:
    59  
    60  - `namespace`: Namespace to run Kubernetes Pods in
    61  - `namespace_overwrite_allowed`: Regular expression to validate the contents of
    62    the namespace overwrite environment variable (documented following). When empty,
    63    it disables the namespace overwrite feature
    64  - `privileged`: Run containers with the privileged flag
    65  - `cpu_limit`: The CPU allocation given to build containers
    66  - `memory_limit`: The amount of memory allocated to build containers
    67  - `service_cpu_limit`: The CPU allocation given to build service containers
    68  - `service_memory_limit`: The amount of memory allocated to build service containers
    69  - `helper_cpu_limit`: The CPU allocation given to build helper containers
    70  - `helper_memory_limit`: The amount of memory allocated to build helper containers
    71  - `cpu_request`: The CPU allocation requested for build containers
    72  - `memory_request`: The amount of memory requested from build containers
    73  - `service_cpu_request`: The CPU allocation requested for build service containers
    74  - `service_memory_request`: The amount of memory requested for build service containers
    75  - `helper_cpu_request`: The CPU allocation requested for build helper containers
    76  - `helper_memory_request`: The amount of memory requested for build helper containers
    77  - `pull_policy`: specify the image pull policy: `never`, `if-not-present`, `always`. The cluster default will be used if not set.
    78  - `node_selector`: A `table` of `key=value` pairs of `string=string`. Setting this limits the creation of pods to kubernetes nodes matching all the `key=value` pairs
    79  - `node_tolerations`: A `table` of `"key=value" = "Effect"` pairs in the format of `string=string:string`. Setting this allows pods to schedule to nodes with all or a subset of tolerated taints. Only one toleration can be supplied through environment variable configuration. The `key`, `value`, and `effect` match with the corresponding field names in kubernetes pod toleration configuration. 
    80  - `image_pull_secrets`: A array of secrets that are used to authenticate docker image pulling
    81  - `helper_image`: [ADVANCED] Override the default helper image used to clone repos and upload artifacts. Read the [helper image][advanced-configuration-helper-image] section of _advanced configuration_ page for more details
    82  - `terminationGracePeriodSeconds`: Duration after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal
    83  - `poll_interval`: How frequently, in seconds, the runner will poll the Kubernetes pod it has just created to check its status. [Default: 3]
    84  - `poll_timeout`: The amount of time, in seconds, that needs to pass before the runner will timeout attempting to connect to the container it has just created (useful for queueing more builds that the cluster can handle at a time) [Default: 180]
    85  - `pod_labels`: A set of labels to be added to each build pod created by the runner. The value of these can include environment variables for expansion.
    86  - `pod_annotations`: A set of annotations to be added to each build pod created by the Runner. The value of these can include environment variables for expansion. Pod annotations can be overwritten in each build.
    87  - `pod_annotations_overwrite_allowed`: Regular expression to validate the contents of
    88    the pod annotations overwrite environment variable. When empty,
    89      it disables the pod annotations overwrite feature
    90  - `service_account`: default service account to be used for making kubernetes api calls.
    91  - `service_account_overwrite_allowed`: Regular expression to validate the contents of
    92    the service account overwrite environment variable. When empty,
    93      it disables the service account overwrite feature
    94  - `bearer_token`: Default bearer token used to launch build pods.
    95  - `bearer_token_overwrite_allowed`: Boolean to allow projects to specify a bearer token that will be used to create the build pod.
    96  - `volumes`: configured through the config file, the list of volumes that will be mounted in the build container. [Read more about using volumes.](#using-volumes)
    97  
    98  ### Configuring executor Service Account
    99  
   100  You can set the `KUBERNETES_SERVICE_ACCOUNT` environment variable or use `--service-account` flag
   101  
   102  ### Overwriting Kubernetes Namespace
   103  
   104  Additionally, Kubernetes namespace can be overwritten on `.gitlab-ci.yml` file, by using the variable
   105  `KUBERNETES_NAMESPACE_OVERWRITE`.
   106  
   107  This approach allow you to create a new isolated namespace dedicated for CI purposes, and deploy a custom
   108  set of Pods. The `Pods` spawned by the runner will take place on the overwritten namespace, for simple
   109  and straight forward access between container during the CI stages.
   110  
   111  ``` yaml
   112  variables:
   113    KUBERNETES_NAMESPACE_OVERWRITE: ci-${CI_COMMIT_REF_SLUG}
   114  ```
   115  
   116  Furthermore, to ensure only designated namespaces will be used during CI runs, inform the configuration
   117  `namespace_overwrite_allowed` with proper regular expression. When left empty the overwrite behaviour is
   118  disabled.
   119  
   120  ### Overwriting Kubernetes Default Service Account
   121  
   122  Additionally, Kubernetes service account can be overwritten on `.gitlab-ci.yml` file, by using the variable
   123  `KUBERNETES_SERVICE_ACCOUNT_OVERWRITE`.
   124  
   125  This approach allow you to specify a service account that is attached to the namespace, useful when dealing
   126  with complex RBAC configurations.
   127  ``` yaml
   128  variables:
   129    KUBERNETES_SERVICE_ACCOUNT_OVERWRITE: ci-service-account
   130  ```
   131  usefull when overwritting the namespace and RBAC is setup in the cluster.
   132  
   133  To ensure only designated service accounts will be used during CI runs, inform the configuration
   134   `service_account_overwrite_allowed` or set the environment variable `KUBERNETES_SERVICE_ACCOUNT_OVERWRITE_ALLOWED`
   135   with proper regular expression. When left empty the overwrite behaviour is disabled.
   136  
   137  ### Setting Bearer Token to be Used When Making Kubernetes API calls
   138  
   139  In conjunction with setting the namespace and service account as mentioned above, you may set the bearer token used when making API calls to create the build pods.  This will allow project owners to use project secret variables to specify a bearer token.  When specifying the bearer token, it is required that you set the `Host` config keyword.
   140  ``` yaml
   141  variables:
   142    KUBERNETES_BEARER_TOKEN: thebearertokenfromanothernamespace
   143  ```
   144  
   145  ### Overwriting pod annotations
   146  
   147  Additionally, Kubernetes pod annotations can be overwritten on the `.gitlab-ci.yml` file, by using `KUBERNETES_POD_ANNOTATIONS_*` for variables and `key=value` for the value. The pod annotations will be overwritten to the `key=value`. Also, multiple annotations can be applied. For example:
   148  
   149  ```yaml
   150  variables:
   151    KUBERNETES_POD_ANNOTATIONS_1: "Key1=Val1"
   152    KUBERNETES_POD_ANNOTATIONS_2: "Key2=Val2"
   153    KUBERNETES_POD_ANNOTATIONS_3: "Key3=Val3"
   154  ```
   155  
   156  NOTE: **Note:**
   157  You must specify [`pod_annotations_overwrite_allowed`](#the-keywords) to override pod annotations via the `.gitlab-ci.yml` file.
   158  
   159  ## Define keywords in the config toml
   160  
   161  Each of the keywords can be defined in the `config.toml` for the gitlab runner.
   162  
   163  Here is an example `config.toml`:
   164  
   165  ```toml
   166  concurrent = 4
   167  
   168  [[runners]]
   169    name = "Kubernetes Runner"
   170    url = "https://gitlab.com/ci"
   171    token = "......"
   172    executor = "kubernetes"
   173    [runners.kubernetes]
   174      host = "https://45.67.34.123:4892"
   175      cert_file = "/etc/ssl/kubernetes/api.crt"
   176      key_file = "/etc/ssl/kubernetes/api.key"
   177      ca_file = "/etc/ssl/kubernetes/ca.crt"
   178      namespace = "gitlab"
   179      namespace_overwrite_allowed = "ci-.*"
   180      bearer_token_overwrite_allowed = true
   181      privileged = true
   182      cpu_limit = "1"
   183      memory_limit = "1Gi"
   184      service_cpu_limit = "1"
   185      service_memory_limit = "1Gi"
   186      helper_cpu_limit = "500m"
   187      helper_memory_limit = "100Mi"
   188      poll_interval = 5
   189      poll_timeout = 3600
   190      [runners.kubernetes.node_selector]
   191        gitlab = "true"
   192      [runners.kubernetes.node_tolerations]
   193        "node-role.kubernetes.io/master" = "NoSchedule"
   194        "custom.toleration=value" = "NoSchedule"
   195        "empty.value=" = "PreferNoSchedule"
   196  	  "onlyKey" = ""
   197  ```
   198  
   199  ## Using volumes
   200  
   201  As described earlier, volumes can be mounted in the build container.
   202  At this time _hostPath_, _PVC_, _configMap_, and _secret_ volume types
   203  are supported. User can configure any number of volumes for each of
   204  mentioned types.
   205  
   206  Here is an example configuration:
   207  
   208  ```toml
   209  concurrent = 4
   210  
   211  [[runners]]
   212    # usual configuration
   213    executor = "kubernetes"
   214    [runners.kubernetes]
   215      [[runners.kubernetes.volumes.host_path]]
   216        name = "hostpath-1"
   217        mount_path = "/path/to/mount/point"
   218        read_only = true
   219        host_path = "/path/on/host"
   220      [[runners.kubernetes.volumes.host_path]]
   221        name = "hostpath-2"
   222        mount_path = "/path/to/mount/point_2"
   223        read_only = true
   224      [[runners.kubernetes.volumes.pvc]]
   225        name = "pvc-1"
   226        mount_path = "/path/to/mount/point1"
   227      [[runners.kubernetes.volumes.config_map]]
   228        name = "config-map-1"
   229        mount_path = "/path/to/directory"
   230        [runners.kubernetes.volumes.config_map.items]
   231          "key_1" = "relative/path/to/key_1_file"
   232          "key_2" = "key_2"
   233      [[runners.kubernetes.volumes.secret]]
   234        name = "secrets"
   235        mount_path = "/path/to/directory1"
   236        read_only = true
   237        [runners.kubernetes.volumes.secret.items]
   238          "secret_1" = "relative/path/to/secret_1_file"
   239      [[runners.kubernetes.volumes.empty_dir]]
   240        name = "empty_dir"
   241        mount_path = "/path/to/empty_dir"
   242        medium = "Memory"
   243  ```
   244  
   245  ### Host Path volumes
   246  
   247  [_HostPath_ volume][k8s-host-path-volume-docs] configuration instructs Kubernetes to mount
   248  a specified host path inside of the container. The volume can be configured with
   249  following options:
   250  
   251  | Option     | Type    | Required | Description |
   252  |------------|---------|----------|-------------|
   253  | name       | string  | yes      | The name of the volume |
   254  | mount_path | string  | yes      | Path inside of container where the volume should be mounted |
   255  | host_path  | string  | no       | Host's path that should be mounted as volume. If not specified then set to the same path as `mount_path`. |
   256  | read_only  | boolean | no       | Set's the volume in read-only mode (defaults to false) |
   257  
   258  ### PVC volumes
   259  
   260  [_PVC_ volume][k8s-pvc-volume-docs] configuration instructs Kubernetes to use a _PersistentVolumeClaim_
   261  that is defined in Kubernetes cluster and mount it inside of the container. The volume
   262  can be configured with following options:
   263  
   264  | Option     | Type    | Required | Description |
   265  |------------|---------|----------|-------------|
   266  | name       | string  | yes      | The name of the volume and at the same time the name of _PersistentVolumeClaim_ that should be used |
   267  | mount_path | string  | yes      | Path inside of container where the volume should be mounted |
   268  | read_only  | boolean | no       | Set's the volume in read-only mode (defaults to false) |
   269  
   270  ### Config Map volumes
   271  
   272  _ConfigMap_ volume configuration instructs Kubernetes to use a [_configMap_][k8s-config-map-docs]
   273  that is defined in Kubernetes cluster and mount it inside of the container.
   274  
   275  | Option     | Type    | Required | Description |
   276  |------------|---------|----------|-------------|
   277  | name       | string  | yes      | The name of the volume and at the same time the name of _configMap_ that should be used |
   278  | mount_path | string  | yes      | Path inside of container where the volume should be mounted |
   279  | read_only  | boolean | no       | Set's the volume in read-only mode (defaults to false) |
   280  | items      | map[string]string | no | Key-to-path mapping for keys from the _configMap_ that should be used. |
   281  
   282  When using _configMap_ volume, each key from selected _configMap_ will be changed into a file
   283  stored inside of the selected mount path. By default all keys are present, _configMap's_ key
   284  is used as file's name and value is stored as file's content. The default behavior can be
   285  changed with `items` option.
   286  
   287  `items` option is defining a mapping between key that should be used and path (relative
   288  to volume's mount path) where _configMap's_ value should be saved. When using `items` option
   289  **only selected keys** will be added to the volumes and all other will be skipped.
   290  
   291  > **Notice**: If a non-existing key will be used then job will fail on Pod creation stage.
   292  
   293  ### Secret volumes
   294  
   295  [_Secret_ volume][k8s-secret-volume-docs] configuration instructs Kubernetes to use
   296  a _secret_ that is defined in Kubernetes cluster and mount it inside of the container.
   297  
   298  | Option     | Type    | Required | Description |
   299  |------------|---------|----------|-------------|
   300  | name       | string  | yes      | The name of the volume and at the same time the name of _secret_ that should be used |
   301  | mount_path | string  | yes      | Path inside of container where the volume should be mounted |
   302  | read_only  | boolean | no       | Set's the volume in read-only mode (defaults to false) |
   303  | items      | map[string]string | no | Key-to-path mapping for keys from the _secret_ that should be used. |
   304  
   305  When using _secret_ volume each key from selected _secret_ will be changed into a file
   306  stored inside of the selected mount path. By default all keys are present, _secret's_ key
   307  is used as file's name and value is stored as file's content. The default behavior can be
   308  changed with `items` option.
   309  
   310  `items` option is defining a mapping between key that should be used and path (relative
   311  to volume's mount path) where _secret's_ value should be saved. When using `items` option
   312  **only selected keys** will be added to the volumes and all other will be skipped.
   313  
   314  > **Notice**: If a non-existing key will be used then job will fail on Pod creation stage.
   315  
   316  ### Empty Dir volumes
   317  
   318  [_emptyDir_ volume][k8s-empty-dir-volume-docs] configuration instructs Kubernetes to mount an empty directory inside of the container.
   319  
   320  | Option     | Type    | Required | Description |
   321  |------------|---------|----------|-------------|
   322  | name       | string  | yes      | The name of the volume |
   323  | mount_path | string  | yes      | Path inside of container where the volume should be mounted |
   324  | medium     | String  | no       | "Memory" will provide a tmpfs, otherwise it defaults to the node disk storage (defaults to "") |
   325  
   326  ## Using Docker in your builds
   327  
   328  There are a couple of caveats when using docker in your builds while running on
   329  a kubernetes cluster. Most of these issues are already discussed in the
   330  [**Using Docker Build**](https://docs.gitlab.com/ee/ci/docker/using_docker_build.html)
   331  section of the gitlab-ci
   332  documentation but it is worth it to revisit them here as you might run into
   333  some slightly different things when running this on your cluster.
   334  
   335  ### Exposing `/var/run/docker.sock`
   336  Exposing your host's `/var/run/docker.sock` into your build container, using the
   337  `runners.kubernetes.volumes.host_path` option, brings the same risks with it as
   338  always. That node's containers are accessible from the build container and
   339  depending if you are running builds in the same cluster as your production
   340  containers it might not be wise to do that.
   341  
   342  ### Using `docker:dind`
   343  Running the `docker:dind` also known as the `docker-in-docker` image is also
   344  possible but sadly needs the containers to be run in privileged mode.
   345  If you're willing to take that risk other problems will arise that might not
   346  seem as straight forward at first glance. Because the docker daemon is started
   347  as a `service` usually in your `.gitlab-ci.yaml` it will be run as a separate
   348  container in your Pod. Basically containers in Pods only share volumes assigned
   349  to them and an IP address by which they can reach each other using `localhost`.
   350  `/var/run/docker.sock` is not shared by the `docker:dind` container and the `docker`
   351  binary tries to use it by default. To overwrite this and make the client use tcp
   352  to contact the docker daemon in the other container be sure to include
   353  `DOCKER_HOST=tcp://localhost:2375` in your environment variables of the build container.
   354  
   355  ### Not supplying git
   356  Do *not* try to use an image that doesn't supply git and add the `GIT_STRATEGY=none`
   357  environment variable for a job that you think doesn't need to do a fetch or clone.
   358  Because Pods are ephemeral and do not keep state of previously run jobs your
   359  checked out code will not exist in both the build and the docker service container.
   360  Error's you might run into are things like `could not find git binary` and
   361  the docker service complaining that it cannot follow some symlinks into your
   362  build context because of the missing code.
   363  
   364  ### Resource separation
   365  In both the `docker:dind` and `/var/run/docker.sock` cases the docker daemon
   366  has access to the underlying kernel of the host machine. This means that any
   367  `limits` that had been set in the Pod will not work when building docker images.
   368  The docker daemon will report the full capacity of the node regardless of
   369  the limits imposed on the docker build containers spawned by kubernetes.
   370  
   371  One way to help minimize the exposure of the host's kernel to any build container
   372  when running in privileged mode or by exposing `/var/run/docker.sock` is to use
   373  the `node_selector` option to set one or more labels that have to match a node
   374  before any containers are deployed to it. For example build containers may only run
   375  on nodes that are labeled with `role=ci` while running all other production services
   376  on other nodes. Further separation of build containers can be achieved using node
   377  [taints](https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/).
   378  This will disallow other pods from scheduling on the same nodes as the
   379  build pods without extra configuration for the other pods.
   380  
   381  ### Using kaniko
   382  
   383  Another approach for building Docker images inside a Kubernetes cluster is using [kaniko](https://github.com/GoogleContainerTools/kaniko).
   384  kaniko:
   385  
   386  - Allows you to build images without privileged access.
   387  - Works without the Docker daemon.
   388  
   389  For more information, see [Building images with kaniko and GitLab CI/CD](https://docs.gitlab.com/ee/ci/docker/using_kaniko.html).
   390  
   391  [k8s-host-path-volume-docs]: https://kubernetes.io/docs/concepts/storage/volumes/#hostpath
   392  [k8s-pvc-volume-docs]: https://kubernetes.io/docs/concepts/storage/volumes/#persistentvolumeclaim
   393  [k8s-secret-volume-docs]: https://kubernetes.io/docs/concepts/storage/volumes/#secret
   394  [k8s-config-map-docs]: https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/
   395  [k8s-empty-dir-volume-docs]:https://kubernetes.io/docs/concepts/storage/volumes/#emptydir
   396  [advanced-configuration-helper-image]: ../configuration/advanced-configuration.md#helper-image