Compare languages | The multitenancy-manager module: usage examples

Default project templates

Шаблоны для проектов доступные по умолчанию

The following project templates are included in the Deckhouse Kubernetes Platform:

В Deckhouse Kubernetes Platform есть набор шаблонов для создания проектов:

  • default — шаблон для базовых сценариев использования проектов:
  • ограничение ресурсов;
  • сетевая изоляция;
  • автоматические алерты и сбор логов;
  • выбор профиля безопасности;
  • настройка администраторов проекта.
  • default — a template that covers basic project use cases:
  • resource limitation;
  • network isolation;
  • automatic alerts and log collection;
  • choice of security profile;
  • project administrators setup.

Описание шаблона в GitHub.

Template description on GitHub.

  • secure — включает все возможности шаблона default, а также дополнительные функции:
  • настройка допустимых для проекта UID/GID;
  • правила аудита обращения Linux-пользователей проекта к ядру;
  • сканирование запускаемых образов контейнеров на наличие известных уязвимостей (CVE).
  • secure — includes all the capabilities of the default template and additional features:
  • setting up permissible UID/GID for the project;
  • audit rules for project users’ access to the Linux kernel;
  • scanning of launched container images for CVE presence.

Описание шаблона в GitHub.

Template description on GitHub.

  • secure-with-dedicated-nodes — включает все возможности шаблона secure, а также дополнительные функции:
  • определение селектора узла для всех подов в проекте: если под создан, селектор узла пода будет автоматически заменён на селектор узла проекта;
  • определение стандартных tolerations для всех подов в проекте: если под создан, стандартные значения tolerations добавляются к нему автоматически.
  • secure-with-dedicated-nodes — includes all the capabilities of the secure template and additional features:
  • defining the node selector for all the pods in the project: if a pod is created, the node selector pod will be substituted with the project’s node selector automatically;
  • defining the default toleration for all the pods in the project: if a pod is created, the default toleration will be added to the pod automatically.

Описание шаблона в GitHub.

Template description on GitHub.

Чтобы перечислить все доступные параметры для шаблона проекта, выполните команду:

To list all available parameters for a project template, execute the command:

shell kubectl get projecttemplates <ИМЯ_ШАБЛОНА_ПРОЕКТА> -o jsonpath='{.spec.parametersSchema.openAPIV3Schema}' | jq

shell kubectl get projecttemplates -o jsonpath='{.spec.parametersSchema.openAPIV3Schema}' | jq

Создание проекта

Creating a project

  1. Для создания проекта создайте ресурс Project с указанием имени шаблона проекта в поле .spec.projectTemplateName.
  2. В параметре .spec.parameters ресурса Project укажите значения параметров для секции .spec.parametersSchema.openAPIV3Schema ресурса ProjectTemplate.
  1. To create a project, create the Project resource by specifying the name of the project template in .spec.projectTemplateName field.
  2. In the .spec.parameters field of the Project resource, specify the parameter values suitable for the ProjectTemplate .spec.parametersSchema.openAPIV3Schema.

Пример создания проекта с помощью ресурса Project из default ProjectTemplate представлен ниже:

Example of creating a project using the Project resource from the default ProjectTemplate:

yaml apiVersion: deckhouse.io/v1alpha2 kind: Project metadata: name: my-project spec: description: This is an example from the Deckhouse documentation. projectTemplateName: default parameters: resourceQuota: requests: cpu: 5 memory: 5Gi storage: 1Gi limits: cpu: 5 memory: 5Gi networkPolicy: Isolated podSecurityProfile: Restricted extendedMonitoringEnabled: true administrators:

  • subject: Group name: k8s-admins

yaml apiVersion: deckhouse.io/v1alpha2 kind: Project metadata: name: my-project spec: description: This is an example from the Deckhouse documentation. projectTemplateName: default parameters: resourceQuota: requests: cpu: 5 memory: 5Gi storage: 1Gi limits: cpu: 5 memory: 5Gi networkPolicy: Isolated podSecurityProfile: Restricted extendedMonitoringEnabled: true administrators:

  • subject: Group name: k8s-admins
  1. Для проверки статуса проекта выполните команду:
  1. To check the status of the project, execute the command:

shell kubectl get projects my-project

shell kubectl get projects my-project

Успешно созданный проект должен отображаться в статусе Deployed (синхронизирован). Если отображается статус Error (ошибка), добавьте аргумент -o yaml к команде (например, kubectl get projects my-project -o yaml) для получения более подробной информации о причине ошибки.

A successfully created project should be in the Deployed state. If the state equals Error, add the -o yaml argument to the command (e.g., kubectl get projects my-project -o yaml) to get more detailed information about the error.

Автоматическое создание проекта для пространства имён

Creating a project automatically for a namespace

Для пространства имён возможно создать новый проект. Для этого пометьте пространство имён аннотацией projects.deckhouse.io/adopt. Например:

You can create a new project for a namespace. To do this, add the projects.deckhouse.io/adopt annotation to the namespace. For example:

  1. Создайте новое пространство имён:
  1. Create a new namespace:

shell kubectl create ns test

shell kubectl create ns test

  1. Пометьте его аннотацией:
  1. Add the annotation:

shell kubectl annotate ns test projects.deckhouse.io/adopt=””

shell kubectl annotate ns test projects.deckhouse.io/adopt=””

  1. Убедитесь, что проект создался:
  1. Make sure that the project was created:

shell kubectl get projects

shell kubectl get projects

В списке проектов появится новый проект, соответствующий пространству имён:

A new project corresponding to the namespace will appear in the project list:

shell NAME STATE PROJECT TEMPLATE DESCRIPTION AGE deckhouse Deployed virtual This is a virtual project 181d default Deployed virtual This is a virtual project 181d test Deployed empty 1m

shell NAME STATE PROJECT TEMPLATE DESCRIPTION AGE deckhouse Deployed virtual This is a virtual project 181d default Deployed virtual This is a virtual project 181d test Deployed empty 1m

Шаблон созданного проекта можно изменить на существующий.

You can change the template of the created project to the existing one.

Обратите внимание, что при смене шаблона может возникнуть конфликт ресурсов: если в чарте шаблона прописаны ресурсы, которые уже присутствуют в пространстве имён, то применить шаблон не получится.

Note that changing the template may cause a resource conflict. If the template chart contains resources that are already present in the namespace, you will not be able to apply the template.

Создание собственного шаблона для проекта

Creating your own project template

Шаблоны проектов по умолчанию включают базовые сценарии использования и служат примером возможностей шаблонов.

Default templates cover basic project use cases and serve as a good example of template capabilities.

Для создания своего шаблона:

  1. Возьмите за основу один из шаблонов по умолчанию, например, default.
  2. Скопируйте его в отдельный файл, например, my-project-template.yaml при помощи команды:

To create your own template:

  1. Take one of the default templates as a basis, for example, default.
  2. Copy it to a separate file, for example, my-project-template.yaml using the command:

shell kubectl get projecttemplates default -o yaml > my-project-template.yaml

shell kubectl get projecttemplates default -o yaml > my-project-template.yaml

  1. Отредактируйте файл my-project-template.yaml, внесите в него необходимые изменения.
  1. Edit the my-project-template.yaml file, make the necessary changes.

Необходимо изменить не только шаблон, но и схему входных параметров под него.

Шаблоны для проектов поддерживают все функции шаблонизации Helm.

  1. Измените имя шаблона в поле .metadata.name.
  2. Примените полученный шаблон командой:

It is necessary to change not only the template, but also the scheme of input parameters for it.

Project templates support all Helm templating functions.

shell kubectl apply -f my-project-template.yaml

  1. Change the template name in the .metadata.name field.
  2. Apply your new template with the command:
  1. Проверьте доступность нового шаблона с помощью команды:

shell kubectl apply -f my-project-template.yaml

shell kubectl get projecttemplates <ИМЯ_НОВОГО_ШАБЛОНА>

  1. Check the availability of the new template with the command:

shell kubectl get projecttemplates