init
This commit is contained in:
131
03-mutation/03-advanced/README.md
Normal file
131
03-mutation/03-advanced/README.md
Normal file
@@ -0,0 +1,131 @@
|
||||
# Урок 3.3 — Продвинутые техники мутации и переменные
|
||||
|
||||
## Файлы
|
||||
|
||||
| Файл | Описание |
|
||||
|------|----------|
|
||||
| `kyverno-global-config.yaml` | ConfigMap с централизованными настройками |
|
||||
| `set-dynamic-resource-limits.yaml` | Лимиты из ConfigMap по типу сервиса |
|
||||
| `add-creator-audit-annotation.yaml` | Автоматический audit trail |
|
||||
|
||||
## Подготовка
|
||||
|
||||
```bash
|
||||
# Сначала создать ConfigMap с конфигурацией
|
||||
kubectl apply -f kyverno-global-config.yaml
|
||||
|
||||
# Затем политики
|
||||
kubectl apply -f set-dynamic-resource-limits.yaml
|
||||
kubectl apply -f add-creator-audit-annotation.yaml
|
||||
```
|
||||
|
||||
## Тест динамических лимитов
|
||||
|
||||
```bash
|
||||
# Pod типа "api" — получит 512Mi/500m
|
||||
kubectl apply -f - <<EOF
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
metadata:
|
||||
name: api-pod
|
||||
namespace: default
|
||||
labels:
|
||||
service-type: api
|
||||
spec:
|
||||
containers:
|
||||
- name: app
|
||||
image: nginx:1.25.3
|
||||
EOF
|
||||
|
||||
kubectl get pod api-pod -o jsonpath='{.spec.containers[0].resources}' | jq .
|
||||
# Ожидаем: limits.memory=512Mi, limits.cpu=500m
|
||||
|
||||
# Pod типа "worker" — получит 1Gi/250m
|
||||
kubectl apply -f - <<EOF
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
metadata:
|
||||
name: worker-pod
|
||||
namespace: default
|
||||
labels:
|
||||
service-type: worker
|
||||
spec:
|
||||
containers:
|
||||
- name: app
|
||||
image: nginx:1.25.3
|
||||
EOF
|
||||
|
||||
kubectl get pod worker-pod -o jsonpath='{.spec.containers[0].resources}' | jq .
|
||||
# Ожидаем: limits.memory=1Gi, limits.cpu=250m
|
||||
|
||||
# Изменить дефолты без изменения политики
|
||||
kubectl edit configmap kyverno-global-config -n kyverno
|
||||
# Измените default_memory: "512Mi", сохраните
|
||||
# Новые поды получат новые дефолты (~30-60 сек на обновление кэша)
|
||||
|
||||
# Удалить тесты
|
||||
kubectl delete pod api-pod worker-pod
|
||||
```
|
||||
|
||||
## JMESPath функции — шпаргалка
|
||||
|
||||
```yaml
|
||||
# Строки
|
||||
{{ to_upper('hello') }} # HELLO
|
||||
{{ to_lower('WORLD') }} # world
|
||||
{{ trim(' spaces ') }} # spaces
|
||||
{{ split('a,b,c', ',') }} # ["a","b","c"]
|
||||
{{ join(['a','b','c'], '-') }} # a-b-c
|
||||
{{ replace_all('foo/bar', '/', '-') }} # foo-bar
|
||||
{{ truncate('long string', 5) }} # long
|
||||
|
||||
# Числа
|
||||
{{ to_number('42') }} # 42
|
||||
{{ divide(`10`, `3`) }} # 3.333
|
||||
|
||||
# Условия (Elvis operator)
|
||||
{{ request.object.metadata.labels.env || 'default' }}
|
||||
|
||||
# Массивы
|
||||
{{ length(request.object.spec.containers) }}
|
||||
{{ request.object.spec.containers[0].name }}
|
||||
{{ request.object.spec.containers[].name }} # все имена
|
||||
|
||||
# Время
|
||||
{{ time_now_utc() }} # текущее UTC время
|
||||
```
|
||||
|
||||
## Тест audit аннотаций
|
||||
|
||||
```bash
|
||||
kubectl apply -f - <<EOF
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: test-audit
|
||||
namespace: default
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: test
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: test
|
||||
spec:
|
||||
containers:
|
||||
- name: app
|
||||
image: nginx:1.25.3
|
||||
resources:
|
||||
limits:
|
||||
memory: "128Mi"
|
||||
cpu: "100m"
|
||||
EOF
|
||||
|
||||
kubectl get deployment test-audit \
|
||||
-o jsonpath='{.metadata.annotations}' | jq .
|
||||
# Увидите: created-by, created-at, user-groups
|
||||
|
||||
kubectl delete deployment test-audit
|
||||
```
|
||||
34
03-mutation/03-advanced/add-creator-audit-annotation.yaml
Normal file
34
03-mutation/03-advanced/add-creator-audit-annotation.yaml
Normal file
@@ -0,0 +1,34 @@
|
||||
apiVersion: kyverno.io/v1
|
||||
kind: ClusterPolicy
|
||||
metadata:
|
||||
name: add-creator-audit-annotation
|
||||
annotations:
|
||||
policies.kyverno.io/title: "Аннотация аудита создателя ресурса"
|
||||
policies.kyverno.io/category: Governance
|
||||
policies.kyverno.io/severity: low
|
||||
policies.kyverno.io/subject: Deployment,StatefulSet
|
||||
policies.kyverno.io/description: >-
|
||||
При создании Deployment или StatefulSet автоматически добавляет
|
||||
аннотации: кто создал, когда, из каких групп.
|
||||
Создаёт автоматический audit trail без дополнительных инструментов.
|
||||
spec:
|
||||
rules:
|
||||
- name: add-creator-annotation
|
||||
match:
|
||||
resources:
|
||||
kinds:
|
||||
- Deployment
|
||||
- StatefulSet
|
||||
preconditions:
|
||||
any:
|
||||
- key: "{{ request.operation }}"
|
||||
operator: Equals
|
||||
value: CREATE
|
||||
mutate:
|
||||
patchStrategicMerge:
|
||||
metadata:
|
||||
annotations:
|
||||
audit.company.com/created-by: "{{ request.userInfo.username }}"
|
||||
audit.company.com/created-at: "{{ time_now_utc() }}"
|
||||
audit.company.com/user-groups: >-
|
||||
{{ request.userInfo.groups | join(', ', @) }}
|
||||
22
03-mutation/03-advanced/kyverno-global-config.yaml
Normal file
22
03-mutation/03-advanced/kyverno-global-config.yaml
Normal file
@@ -0,0 +1,22 @@
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: kyverno-global-config
|
||||
namespace: kyverno
|
||||
labels:
|
||||
app: kyverno-config
|
||||
data:
|
||||
# Дефолтные resource limits по типу сервиса
|
||||
api_memory: "512Mi"
|
||||
api_cpu: "500m"
|
||||
worker_memory: "1Gi"
|
||||
worker_cpu: "250m"
|
||||
default_memory: "256Mi"
|
||||
default_cpu: "250m"
|
||||
|
||||
# Node selector defaults
|
||||
default_node_type: "standard"
|
||||
region: "eu-west-1"
|
||||
|
||||
# Allowed registries (через запятую)
|
||||
allowed_registries: "registry.company.com,gcr.io/company-project"
|
||||
44
03-mutation/03-advanced/set-dynamic-resource-limits.yaml
Normal file
44
03-mutation/03-advanced/set-dynamic-resource-limits.yaml
Normal file
@@ -0,0 +1,44 @@
|
||||
apiVersion: kyverno.io/v1
|
||||
kind: ClusterPolicy
|
||||
metadata:
|
||||
name: set-dynamic-resource-limits
|
||||
annotations:
|
||||
policies.kyverno.io/title: "Динамические resource limits из ConfigMap"
|
||||
policies.kyverno.io/category: Resources
|
||||
policies.kyverno.io/severity: low
|
||||
policies.kyverno.io/subject: Pod
|
||||
policies.kyverno.io/description: >-
|
||||
Устанавливает resource limits на основе лейбла service-type пода.
|
||||
Значения берутся из ConfigMap kyverno-global-config в namespace kyverno.
|
||||
Изменение лимитов — это kubectl edit configmap, не изменение политики.
|
||||
Лейблы: service-type: api | worker | (default)
|
||||
spec:
|
||||
rules:
|
||||
- name: set-limits-from-config
|
||||
match:
|
||||
resources:
|
||||
kinds:
|
||||
- Pod
|
||||
exclude:
|
||||
resources:
|
||||
namespaces:
|
||||
- kube-system
|
||||
- kyverno
|
||||
context:
|
||||
- name: globalConfig
|
||||
configMap:
|
||||
name: kyverno-global-config
|
||||
namespace: kyverno
|
||||
mutate:
|
||||
foreach:
|
||||
- list: "request.object.spec.containers"
|
||||
patchStrategicMerge:
|
||||
spec:
|
||||
containers:
|
||||
- name: "{{ element.name }}"
|
||||
resources:
|
||||
limits:
|
||||
+(memory): >-
|
||||
{{ globalConfig.data.\"{{ request.object.metadata.labels.\"service-type\" || 'default' }}_memory\" || '256Mi' }}
|
||||
+(cpu): >-
|
||||
{{ globalConfig.data.\"{{ request.object.metadata.labels.\"service-type\" || 'default' }}_cpu\" || '250m' }}
|
||||
Reference in New Issue
Block a user