Compare languages | Managing nodes: examples

Below are some examples of NodeGroup description, as well as installing the cert-manager plugin for kubectl and setting the sysctl parameter.

Ниже представлены несколько примеров описания NodeGroup, а также установки плагина cert-manager для kubectl и задания параметра sysctl.

Examples of the NodeGroup configuration

Примеры описания NodeGroup

Cloud nodes

Облачные узлы

yaml apiVersion: deckhouse.io/v1 kind: NodeGroup metadata: name: test spec: nodeType: CloudEphemeral cloudInstances: zones:

  • eu-west-1a
  • eu-west-1b minPerZone: 1 maxPerZone: 2 classReference: kind: AWSInstanceClass name: test nodeTemplate: labels: tier: test

yaml apiVersion: deckhouse.io/v1 kind: NodeGroup metadata: name: test spec: nodeType: CloudEphemeral cloudInstances: zones:

  • eu-west-1a
  • eu-west-1b minPerZone: 1 maxPerZone: 2 classReference: kind: AWSInstanceClass name: test nodeTemplate: labels: tier: test

Static nodes

Статические узлы

Use nodeType: Static for physical servers and VMs on Hypervisors.

Для виртуальных машин на гипервизорах или физических серверов используйте статические узлы, указав nodeType: Static в NodeGroup.

An example:

Пример:

yaml apiVersion: deckhouse.io/v1 kind: NodeGroup metadata: name: worker spec: nodeType: Static

yaml apiVersion: deckhouse.io/v1 kind: NodeGroup metadata: name: worker spec: nodeType: Static

Adding nodes to such a group is done manually using the pre-made scripts.

Узлы в такую группу добавляются вручную с помощью подготовленных скриптов.

You can also use a method that adds static nodes using the Cluster API Provider Static.

Также можно использовать способ добавления статических узлов с помощью Cluster API Provider Static.

System nodes

Системные узлы

yaml apiVersion: deckhouse.io/v1 kind: NodeGroup metadata: name: system spec: nodeTemplate: labels: node-role.deckhouse.io/system: “” taints:

  • effect: NoExecute key: dedicated.deckhouse.io value: system nodeType: Static

yaml apiVersion: deckhouse.io/v1 kind: NodeGroup metadata: name: system spec: nodeTemplate: labels: node-role.deckhouse.io/system: “” taints:

  • effect: NoExecute key: dedicated.deckhouse.io value: system nodeType: Static

Adding a static node to a cluster

Добавление статического узла в кластер

Adding a static node can be done manually or using the Cluster API Provider Static.

Добавление статического узла можно выполнить вручную или с помощью Cluster API Provider Static.

Manually

Вручную

Follow the steps below to add a new static node (e.g., VM or bare metal server) to the cluster:

Чтобы добавить новый статический узел (выделенная ВМ, bare-metal-сервер и т. п.) в кластер вручную, выполните следующие шаги:

  1. For CloudStatic nodes in the following cloud providers, refer to the steps outlined in the documentation:
  2. Use the existing one or create a new NodeGroup custom resource (see the example for the NodeGroup called worker). The nodeType parameter for static nodes in the NodeGroup must be Static or CloudStatic.
  3. Get the Base64-encoded script code to add and configure the node.
  1. Для CloudStatic-узлов в облачных провайдерах, перечисленных ниже, выполните описанные в документации шаги:
  2. Используйте существующий или создайте новый custom resource NodeGroup (пример NodeGroup с именем worker). Параметр nodeType в custom resource NodeGroup для статических узлов должен быть Static или CloudStatic.
  3. Получите код скрипта в кодировке Base64 для добавления и настройки узла.

Here is how you can get Base64-encoded script code to add a node to the worker NodeGroup:

Пример получения кода скрипта в кодировке Base64 для добавления узла в NodeGroup worker:

shell NODE_GROUP=worker kubectl -n d8-cloud-instance-manager get secret manual-bootstrap-for-${NODE_GROUP} -o json | jq ‘.data.”bootstrap.sh”’ -r

shell NODE_GROUP=worker kubectl -n d8-cloud-instance-manager get secret manual-bootstrap-for-${NODE_GROUP} -o json | jq ‘.data.”bootstrap.sh”’ -r

  1. Pre-configure the new node according to the specifics of your environment. For example:
    • Add all the necessary mount points to the /etc/fstab file (NFS, Ceph, etc.);
    • Install the necessary packages (e.g., ceph-common);
    • Configure network connectivity between the new node and the other nodes of the cluster.
  2. Connect to the new node over SSH and run the following command, inserting the Base64 string you got in step 2:
  1. Выполните предварительную настройку нового узла в соответствии с особенностями вашего окружения. Например:
    • добавьте необходимые точки монтирования в файл /etc/fstab (NFS, Ceph и т. д.);
    • установите необходимые пакеты (например, ceph-common);
    • настройте сетевую связанность между новым узлом и остальными узлами кластера.
  2. Зайдите на новый узел по SSH и выполните следующую команду, вставив полученную в п. 2 Base64-строку:

shell echo | base64 -d | bash

shell echo | base64 -d | bash

Using the Cluster API Provider Static

С помощью Cluster API Provider Static

A brief example of adding a static node to a cluster using Cluster API Provider Static (CAPS):

Простой пример добавления статического узла в кластер с помощью Cluster API Provider Static (CAPS):

  1. Prepare the necessary resources.
  1. Подготовьте необходимые ресурсы.
  • Allocate a server (or a virtual machine), configure networking, etc. If required, install specific OS packages and add the mount points on the node.
  • Выделите сервер (или виртуальную машину), настройте сетевую связанность и т. п., при необходимости установите специфические пакеты ОС и добавьте точки монтирования которые потребуются на узле.
  • Create a user (caps in the example below) and add it to sudoers by running the following command on the server:
  • Создайте пользователя (в примере — caps) с возможностью выполнять sudo, выполнив на сервере следующую команду:

shell useradd -m -s /bin/bash caps usermod -aG sudo caps

shell useradd -m -s /bin/bash caps usermod -aG sudo caps

  • Allow the user to run sudo commands without having to enter a password. For this, add the following line to the sudo configuration on the server (you can either edit the /etc/sudoers file, or run the sudo visudo command, or use some other method):
  • Разрешите пользователю выполнять команды через sudo без пароля. Для этого на сервере внесите следующую строку в конфигурацию sudo (отредактировав файл /etc/sudoers, выполнив команду sudo visudo или другим способом):

text caps ALL=(ALL) NOPASSWD: ALL

text caps ALL=(ALL) NOPASSWD: ALL

  • Generate a pair of SSH keys with an empty passphrase on the server:
  • Сгенерируйте на сервере пару SSH-ключей с пустой парольной фразой:

shell ssh-keygen -t rsa -f caps-id -C “” -N “”

shell ssh-keygen -t rsa -f caps-id -C “” -N “”

The public and private keys of the caps user will be stored in the caps-id.pub and caps-id files in the current directory on the server.

Публичный и приватный ключи пользователя caps будут сохранены в файлах caps-id.pub и caps-id в текущей папке на сервере.

  • Add the generated public key to the /home/caps/.ssh/authorized_keys file of the caps user by executing the following commands in the keys directory on the server:
  • Добавьте полученный публичный ключ в файл /home/caps/.ssh/authorized_keys пользователя caps, выполнив в директории с ключами на сервере следующие команды:

shell mkdir -p /home/caps/.ssh cat caps-id.pub » /home/caps/.ssh/authorized_keys chmod 700 /home/caps/.ssh chmod 600 /home/caps/.ssh/authorized_keys chown -R caps:caps /home/caps/

shell mkdir -p /home/caps/.ssh cat caps-id.pub » /home/caps/.ssh/authorized_keys chmod 700 /home/caps/.ssh chmod 600 /home/caps/.ssh/authorized_keys chown -R caps:caps /home/caps/

  1. Create a SSHCredentials resource in the cluster:
  1. Создайте в кластере ресурс SSHCredentials.

Run the following command in the user key directory on the server to encode the private key to Base64:

В директории с ключами пользователя на сервере выполните следующую команду для получения закрытого ключа в формате Base64:

shell base64 -w0 caps-id

shell base64 -w0 caps-id

On any computer with kubectl configured to manage the cluster, create an environment variable with the value of the Base64-encoded private key you generated in the previous step:

На любом компьютере с kubectl, настроенным на управление кластером, создайте переменную окружения со значением закрытого ключа созданного пользователя в Base64, полученным на предыдущем шаге:

shell CAPS_PRIVATE_KEY_BASE64=

shell CAPS_PRIVATE_KEY_BASE64=<ЗАКРЫТЫЙ_КЛЮЧ_В_BASE64>

Create a SSHCredentials resource in the cluster (note that from this point on, you have to use kubectl configured to manage the cluster):

Выполните следующую команду, для создания в кластере ресурса SSHCredentials (здесь и далее также используйте kubectl, настроенный на управление кластером):

shell kubectl create -f - «EOF apiVersion: deckhouse.io/v1alpha1 kind: SSHCredentials metadata: name: credentials spec: user: caps privateSSHKey: “${CAPS_PRIVATE_KEY_BASE64}” EOF

shell kubectl create -f - «EOF apiVersion: deckhouse.io/v1alpha1 kind: SSHCredentials metadata: name: credentials spec: user: caps privateSSHKey: “${CAPS_PRIVATE_KEY_BASE64}” EOF

  1. Create a StaticInstance resource in the cluster; specify the IP address of the static node server:
  1. Создайте в кластере ресурс StaticInstance, указав IP-адрес сервера статического узла:

shell kubectl create -f - «EOF apiVersion: deckhouse.io/v1alpha1 kind: StaticInstance metadata: name: static-0 spec: Specify the IP address of the static node server. address: “" credentialsRef: kind: SSHCredentials name: credentials EOF

shell kubectl create -f - «EOF apiVersion: deckhouse.io/v1alpha1 kind: StaticInstance metadata: name: static-0 spec: Укажите IP-адрес сервера статического узла. address: “" credentialsRef: kind: SSHCredentials name: credentials EOF

  1. Create a NodeGroup resource in the cluster:
  1. Создайте в кластере ресурс NodeGroup:

shell kubectl create -f - «EOF apiVersion: deckhouse.io/v1 kind: NodeGroup metadata: name: worker spec: nodeType: Static staticInstances: count: 1 EOF

shell kubectl create -f - «EOF apiVersion: deckhouse.io/v1 kind: NodeGroup metadata: name: worker spec: nodeType: Static staticInstances: count: 1 EOF

Using the Cluster API Provider Static and label selector filters

С помощью Cluster API Provider Static и фильтрами в label selector

This example shows how you can use filters in the StaticInstance label selector to group static nodes and use them in different NodeGroups. Here, two node groups (front and worker) are used for different tasks. Each group includes nodes with different characteristics — the front group has two servers and the worker group has one.

Пример использования фильтров в label selector StaticInstance, для группировки статических узлов и использования их в разных NodeGroup. В примере используются две группы узлов (front и worker), предназначенные для разных задач, которые должны содержать разные по характеристикам узлы — два сервера для группы front и один для группы worker.

  1. Prepare the required resources (3 servers or virtual machines) and create the SSHCredentials resource in the same way as step 1 and step 2 of the example.
  1. Подготовьте необходимые ресурсы (3 сервера или виртуальные машины) и создайте ресурс SSHCredentials, аналогично п.1 и п.2 примера.
  1. Create two NodeGroup in the cluster (from this point on, use kubectl configured to manage the cluster):
  1. Создайте в кластере два ресурса NodeGroup (здесь и далее используйте kubectl, настроенный на управление кластером):

shell kubectl create -f - «EOF apiVersion: deckhouse.io/v1 kind: NodeGroup metadata: name: front spec: nodeType: Static staticInstances: count: 2 labelSelector: matchLabels: role: front — apiVersion: deckhouse.io/v1 kind: NodeGroup metadata: name: worker spec: nodeType: Static staticInstances: count: 1 labelSelector: matchLabels: role: worker EOF

shell kubectl create -f - «EOF apiVersion: deckhouse.io/v1 kind: NodeGroup metadata: name: front spec: nodeType: Static staticInstances: count: 2 labelSelector: matchLabels: role: front — apiVersion: deckhouse.io/v1 kind: NodeGroup metadata: name: worker spec: nodeType: Static staticInstances: count: 1 labelSelector: matchLabels: role: worker EOF

  1. Create StaticInstance resources in the cluster and specify the valid IP addresses of the servers:
  1. Создайте в кластере ресурсы StaticInstance, указав актуальные IP-адреса серверов:

shell kubectl create -f - «EOF apiVersion: deckhouse.io/v1alpha1 kind: StaticInstance metadata: name: static-front-1 labels: role: front spec: address: “" credentialsRef: kind: SSHCredentials name: credentials --- apiVersion: deckhouse.io/v1alpha1 kind: StaticInstance metadata: name: static-front-2 labels: role: front spec: address: "" credentialsRef: kind: SSHCredentials name: credentials --- apiVersion: deckhouse.io/v1alpha1 kind: StaticInstance metadata: name: static-worker-1 labels: role: worker spec: address: "" credentialsRef: kind: SSHCredentials name: credentials EOF

shell kubectl create -f - «EOF apiVersion: deckhouse.io/v1alpha1 kind: StaticInstance metadata: name: static-front-1 labels: role: front spec: address: “" credentialsRef: kind: SSHCredentials name: credentials --- apiVersion: deckhouse.io/v1alpha1 kind: StaticInstance metadata: name: static-front-2 labels: role: front spec: address: "" credentialsRef: kind: SSHCredentials name: credentials --- apiVersion: deckhouse.io/v1alpha1 kind: StaticInstance metadata: name: static-worker-1 labels: role: worker spec: address: "" credentialsRef: kind: SSHCredentials name: credentials EOF

An example of the NodeUser configuration

Пример описания NodeUser

yaml apiVersion: deckhouse.io/v1 kind: NodeUser metadata: name: testuser spec: uid: 1100 sshPublicKeys:

  • " passwordHash: isSudoer: true

yaml apiVersion: deckhouse.io/v1 kind: NodeUser metadata: name: testuser spec: uid: 1100 sshPublicKeys:

  • " passwordHash: isSudoer: true

An example of the NodeGroupConfiguration configuration

Пример описания NodeGroupConfiguration

Installing the cert-manager plugin for kubectl on master nodes

Установка плагина cert-manager для kubectl на master-узлах

yaml apiVersion: deckhouse.io/v1alpha1 kind: NodeGroupConfiguration metadata: name: add-cert-manager-plugin.sh spec: weight: 100 bundles:

  • “*” nodeGroups:
  • “master” content: | if [ -x /usr/local/bin/kubectl-cert_manager ]; then exit 0 fi curl -L https://github.com/cert-manager/cert-manager/releases/download/v1.7.1/kubectl-cert_manager-linux-amd64.tar.gz -o - | tar -zxvf - kubectl-cert_manager mv kubectl-cert_manager /usr/local/bin

yaml apiVersion: deckhouse.io/v1alpha1 kind: NodeGroupConfiguration metadata: name: add-cert-manager-plugin.sh spec: weight: 100 bundles:

  • “*” nodeGroups:
  • “master” content: | if [ -x /usr/local/bin/kubectl-cert_manager ]; then exit 0 fi curl -L https://github.com/cert-manager/cert-manager/releases/download/v1.7.1/kubectl-cert_manager-linux-amd64.tar.gz -o - | tar -zxvf - kubectl-cert_manager mv kubectl-cert_manager /usr/local/bin

Tuning sysctl parameters

Задание параметра sysctl

yaml apiVersion: deckhouse.io/v1alpha1 kind: NodeGroupConfiguration metadata: name: sysctl-tune.sh spec: weight: 100 bundles:

  • “*” nodeGroups:
  • “*” content: | sysctl -w vm.max_map_count=262144

yaml apiVersion: deckhouse.io/v1alpha1 kind: NodeGroupConfiguration metadata: name: sysctl-tune.sh spec: weight: 100 bundles:

  • “*” nodeGroups:
  • “*” content: | sysctl -w vm.max_map_count=262144