Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kubernetes vault #12

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
4 changes: 3 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
"https://raw.githubusercontent.com/yannh/kubernetes-json-schema/master/v1.22.4-standalone-strict/all.json": "file:///home/urhero/otus/lesson1/yourh3ro_repo/kubernetes-intro/%20namespace.yaml%20"
},
"vs-kubernetes": {
"disable-linters": ["resource-limits"]
"disable-linters": ["resource-limits"],
"vs-kubernetes.helm-path": "/usr/local/bin/helm",
"vs-kubernetes.kubectl-path": "/usr/local/bin/kubectl"
}
}
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,26 @@
# Репозиторий для выполнения домашних заданий курса "Инфраструктурная платформа на основе Kubernetes-2024-02"

[ДЗ#2 Kubernetes controllers. ReplicaSet, Deployment, DaemonSet](kubernetes-controllers/README.md)
[ДЗ#3 Сетевое взаимодействие Pod, сервисы](kubernetes-networks/README.md)
[ДЗ#4 Volumes, StorageClass, PV, PVC](kubernetes-volumes/README.md)
[ДЗ#5 Настройка сервисных аккаунтов и ограничение прав для них](kubernetes-security/README.md)
[ДЗ#6 Шаблонизация манифестов приложения, использование Helm. Установка community Helm charts.](kubernetes-templating/README.md)
[ДЗ#7 Создание собственного CRD](kubernetes-operators/README.md)
[ДЗ#8 Мониторинг приложения в кластере](kubernetes-monitoring/README.md)
[ДЗ#9 Сервисы централизованного логирования для Kubernetes](kubernetes-logging/README.md)
[ДЗ#10 GitOps и инструменты поставки](kubernetes-gitops/README.md)
[ДЗ#11 Хранилище секретов для приложения. Vault.](kubernetes-vault/README.md)
## Tricks, Tools, Hints

### k9s
[K9s - Kubernetes CLI To Manage Your Clusters In Style!](https://github.com/derailed/k9s) - CUI for k8s clusters
https://habr.com/ru/companies/flant/articles/524196/ - статья по функция и возможностям

Установка:
На странице есть инструкции пол установке под все платформы.
Для Ubuntu 22.04.4 LTS (WSL2)
```sh
curl -L https://github.com/derailed/k9s/releases/download/v0.32.4/k9s_linux_amd64.deb -o k9s.deb
sudo dpkg -i k9s.deb
```

Binary file added img/image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image10.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image11.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image12.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image13.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image14.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image15.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image16.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image17.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image18.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image5.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image6.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image7.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image8.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added img/image9.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
91 changes: 91 additions & 0 deletions kubernetes-controllers/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
## ДЗ#2 Kubernetes controllers. ReplicaSet, Deployment, DaemonSet

### Задания:
- Необходимо создать манифест namespace.yaml для namespace с именем homework
- Необходимо создать манифест deployment.yaml. Он должен описывать deployment, который:
- Будет создаваться в namespace homework
- Запускает 3 экземпляра пода, полностью аналогичной по спецификации прошлому ДЗ.
- В дополнение к этому будет иметь readiness пробу, проверяющую наличие файла /homework/index.html
- Будет иметь стратегию обновления RollingUpdate, настроенную так, что в процессе обновления может быть недоступен максимум 1 под

#### Задание с *
- Добавить к манифесту deployment-а спецификацию, обеспечивающую запуск подов деплоймента, только на нодах кластера, имеющих метку homework=true

### Подготовка
1. Необходимо убедиться, что на ноде есть label `homework=true`, это можно посмотреть командой `kubectl get nodes --show-labels`. В моем случае, label уже есть на нужной ноде. Если label нет, его необходимо создать командой `kubectl label nodes <node-name> homework=true`

![alt text](.../img/image.png)

### Запуск
1. Создать namespace командой `kubectl apply -f kubernetes-controllers/namespase.yaml`
2. Создать остальные ресурсы командой `kubectl apply -f kubernetes-controllers/`

![alt text](../img/image2.png)

### Описание решения
1. За создание namespace отвечает файл `kubernetes-controllers/namespase.yaml`, который создает namespace с именем `homework`.
2. Файл `kubernetes-controllers/configmap-nginx-config.yaml` конфигурирует nginx, наследован из Д3#1
3. В файле `kubernetes-controllers/deployment.yaml`
Создает в namespace `homework`

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: webserver
namespace: homework
```

3 экземляра пода, под nginx из ДЗ#1

```yaml
spec:
...
replicas: 3
```

Сконфигурирована readiness probe, которая командой `test -s /homework/index.html` проверяет наличие файла `/homework/index.html` и что файл не пуст.

```yaml
readinessProbe:
exec:
command:
- sh
- -c
- test -s /homework/index.html
initialDelaySeconds: 5
periodSeconds: 5
failureThreshold: 3
```

Сконфигурирована стратегия обновления RollingUpdate, в процессе обновления недоступен максимум 1 pod (`maxUnavailable: 1`)

```yaml
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 1
```

Поды запускаются только на нодах кластера, у которых есть label `homework=true`

```yaml
nodeSelector:
homework: "true"
```

### Проверка
1. Если на нодах нет label `homework=true`, поды не запустятся. Если назначить label, pod-ы запускаются. Эти события видно через `kubectl get events --namespace homework | grep FailedScheduling`

![alt text](../img/image3.png)
![alt text](../img/image5.png)

2. Если удалить из контейнера пода `/homework/index.html`, он переидет в состояние `READY 0/1`, так как readinessProbe оканчивается ошибкой. Эти события так же видно в `kubectl get events --namespace homework | grep Unhealthy`. Для production систем необходимо сконфигурировать `restartPolicy` для подов, но здесь не сконфигурировано для наглядности:

![alt text](../img/image4.png)
![alt text](../img/image6.png)

3. Для проверки `strategy`, необходимо обновить в `deployment.yaml`, для примера я обновили image nginx с `nginx:1.25.5-bookworm` на `nginx:1.26.0-bookworm`. Поды перезапускаются по одному.

![alt text](../img/image7.png)
16 changes: 16 additions & 0 deletions kubernetes-controllers/configmap-nginx-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: nginx-config
namespace: homework
data:
nginx.conf: |
server {
listen 8000;
server_name localhost;

location / {
root /homework;
index index.html;
}
}
67 changes: 67 additions & 0 deletions kubernetes-controllers/deployment.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: webserver
namespace: homework
labels:
app: webserver
spec:
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 1
replicas: 3
selector:
matchLabels:
app: webserver
template:
metadata:
labels:
app: webserver
spec:
initContainers:
- name: init-websever
image: busybox:1.36.1
command: ["/bin/sh", "-c"]
volumeMounts:
- name: homework-vol
mountPath: /init
args:
- wget -O /init/index.html https://github.com/ || echo '$(date)\n Failed wget to https://github.com/' > /init/index.html

containers:
- name: webserver
image: nginx:1.26.0-bookworm
ports:
- containerPort: 8000
volumeMounts:
- name: homework-vol
mountPath: /homework
- name: nginx-conf
mountPath: /etc/nginx/conf.d/
readOnly: true
lifecycle:
preStop:
exec:
command: ["rm", "-f", "/homework/index.html"]
readinessProbe:
exec:
command:
- sh
- -c
- test -s /homework/index.html
initialDelaySeconds: 5
periodSeconds: 5
failureThreshold: 3

volumes:
- name: homework-vol
emptyDir:
sizeLimit: 250Mi
- name: nginx-conf
configMap:
name: nginx-config

nodeSelector:
homework: "true"
4 changes: 4 additions & 0 deletions kubernetes-controllers/namespase.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
apiVersion: v1
kind: Namespace
metadata:
name: homework
160 changes: 160 additions & 0 deletions kubernetes-gitops/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
## ДЗ#10 GitOps и инструменты поставки

### Задания:
- Данное задание будет выполняться в managed k8s в Yandex cloud.
- Разверните managed Kubernetes кластер в Yandex cloud любым удобным вам способом.
- Для кластера создайте два пула нод:
- Для рабочей нагрузки (можно 1 ноду).
- Для инфраструктурных сервисов (также хватит пока и одной ноды).
- Для инфраструктурной ноды/нод добавьте taint, запрещающий на неё планирование подов с посторонней нагрузкой - node-role=infra:NoSchedule.
- Приложите к ДЗ вывод команд kubectl get node -o wide --show-labels и kubectl get nodes -o custom-columns=NAME:.metadata.name,TAINTS:.spec.taints показывающий конфигурацию нод в вашем кластере.
- Установите в кластер ArgoCD с помощью Helm-чарта.
- Необходимо сконфигурировать параметры установки так, чтобы компонент ArgoCD устанавливался исключительно на infra-ноду (добавить соответствующий toleration для обхода taint, а также nodeSelector или nodeAffinity на ваш выбор, для планирования подов только на заданные ноды).
- Приложите к ДЗ values.yaml конфигурации установки ArgoCD и команду самой установки чарта.
- Создайте project с именем Otus.
- В качестве Source-репозитория укажите ваш репозиторий с ДЗ курса.
- В качестве Destination должен быть указан ваш кластер, в который установлен ArgoCD.
- Приложите манифест, описывающий project к ДЗ.
- Создайте приложение ArgoCD
- В качестве репозиторию укажите ваше приложение из ДЗ
kubernetes-networks
- Sync policy – manual
- Namespace - homework
- Проект – Otus. Убедитесь, что есть необходимые настройки,
длю созданию и установки в namespace, который описан в ДЗ
kubernetes-networks
- Убедитесь, что nodeSelector позволюет установить
приложение на одну из нод кластера
- Приложите манифест, описывающий установку приложению
к результатам ДЗ
- Создайте приложение ArgoCD
- В качестве репозиторию укажите ваше приложение из ДЗ
kubernetes-templating
- Укажите директорию, в которой находитсю ваш helm-чарт,
который вы разрабатывали самостоютельно
- SyncPolicy – Auto, AutoHeal – true, Prune – true.
- Проект – Otus.
- Namespace – HomeworkHelm. Убедитесь, что установка чарта
будет остуществлютьсю в отличный от первого приложению
namespace.
- Параметр, задающий количество реплик запускаемого
приложению должен переопределютьсю в конфигураøии
- Приложите манифест, описывающий установку приложению
к результатам ДЗ
- Namespace – HomeworkHelm. Убедитесь, что установка чарта будет осуществляться в отличный от первого приложения namespace.
- Параметр, задающий количество реплик запускаемого приложения должен переопределяться в конфигурации.
- Приложите манифест, описывающий установку приложения к результатам ДЗ.
### Запуск
- Создать в yc необходимые ресурсы согласно описанию (Я это сделал в прошлом ДЗ)
- Добавить в helm репозитории grafana/grafana
- helm install arocd --create-namespace ./argocd
- kubectl apply -f argo

### Описание решения
#### Настройка планирования ArgoCD на Infra nodes
```
helm pull bitnami/argo-cd --untar
```
Аналогично прошлому ДЗ, я сделал pull чарта argocd и в файлах values.yaml и ./argo-cd/charts/redis/values.yaml настроил необходимые параметры:
```yaml
# Для планирования на infra nod-ы
# Сделал для всех ресурсов
...
nodeSelector:
node-role: infra
tolerations:
- key: node-role
operator: Equal
value: infra
effect: NoSchedule
...
```
Далее с помощью команды:
```sh
helm install argocd argo-cd/ --namespace argocd --create-namespace
```
Установил в кластер argo-cd
Далее прешел к настройки ароекта и приложений:
Файл проекта:
```yaml
apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
# Название проекта
name: otus-project
namespace: argocd
spec:
description: Otus homework project
sourceRepos:
# source repo - репозиторий домашних заданий
- 'https://github.com/Kuber-2024-04OTUS/yourh3ro_repo.git'
destinations:
# Любые namespace в текущем кластере
- namespace: '*'
server: 'https://kubernetes.default.svc'
name: in-cluster
# Разрешаю управеление любыми ресурсами, нужно для создания namespaces самим argocd
clusterResourceWhitelist:
- group: '*'
kind: '*'
```
Приложение kubernetes-networks-app:
```yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: kubernetes-networks-app
namespace: argocd
spec:
project: otus-project
source:
# Каталог с приложением
path: kubernetes-networks
# репозиторий домашних заданий
repoURL: https://github.com/Kuber-2024-04OTUS/yourh3ro_repo.git
# ветка репозитория
targetRevision: main
# Проходимя по директорям рекурсивно
directory:
recurse: true
# точна назначения
destination:
# локальный кластер
server: https://kubernetes.default.svc
# namespace в который будет деплоиться приложение
namespace: homework
## SyncPolicy manual используется по-умолчанию
```

Приложение kubernetes-templating-app:
```yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: kubernetes-tempalting-app
namespace: argocd
spec:
project: otus-project
source:
path: kubernetes-templating/task1/otusapp-chart
repoURL: https://github.com/Kuber-2024-04OTUS/yourh3ro_repo.git
# Так как на момент написания ДЗ kubernetes-tempalting ветк не смержена в main, указываю ветку kubernetes-tempalting
targetRevision: kubernetes-tempalting
directory:
recurse: true
destination:
server: https://kubernetes.default.svc
namespace: HomeworkHelm
# Задаю SyncPolicy согласно ДЗ
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=true
```
После применения в кластер:
```
kubectl apply -f argo
```
В argocd создается проект otus-project и 2 приложения. Приложение kubernetes-templating-app деплоится автоматически, а kubernetes-networks-app задеплоится если нажать Sync
Loading
Loading