Aller au contenu principal

Kubernetes & Infrastructure as Code

Guide de deploiement Kubernetes et Infrastructure as Code (IaC) pour MyTelevision API.

Structure des repertoires

mytelevision-api/
├── iac/ # Terraform Infrastructure
│ ├── modules/ # Modules reutilisables
│ │ ├── network/ # VPC, Subnets, Security Groups
│ │ ├── compute/ # ECS/EKS, Auto Scaling
│ │ ├── database/ # RDS PostgreSQL
│ │ ├── storage/ # S3/R2, CloudFront
│ │ ├── observability/ # CloudWatch, Prometheus
│ │ └── security/ # IAM, Secrets Manager, KMS
│ ├── environments/ # Configurations par environnement
│ │ ├── dev/
│ │ ├── staging/
│ │ └── prod/
│ └── shared/ # Configuration partagee
├── k8s/ # Manifestes Kubernetes
│ ├── base/ # Manifestes de base
│ │ ├── namespace.yaml
│ │ ├── configmap.yaml
│ │ ├── secrets.yaml.example
│ │ ├── deployment.yaml
│ │ ├── service.yaml
│ │ ├── ingress.yaml
│ │ ├── hpa.yaml
│ │ ├── pdb.yaml
│ │ ├── serviceaccount.yaml
│ │ └── networkpolicy.yaml
│ └── overlays/
│ ├── staging/
│ │ ├── kustomization.yaml
│ │ └── patches/
│ └── production/
│ ├── kustomization.yaml
│ └── patches/
└── helm/ # Helm Charts
└── mytv-api/
├── Chart.yaml
├── values.yaml
└── templates/

Deploiement Kubernetes

Staging

kubectl apply -k k8s/overlays/staging/

Production

kubectl apply -k k8s/overlays/production/

Verification

# Pods
kubectl get pods -n mytv

# Logs
kubectl logs -f deployment/mytv-api -n mytv

# Describe
kubectl describe deployment mytv-api -n mytv

Manifests Kubernetes

Deployment

apiVersion: apps/v1
kind: Deployment
metadata:
name: mytv-api
namespace: mytv
spec:
replicas: 3
selector:
matchLabels:
app: mytv-api
template:
metadata:
labels:
app: mytv-api
spec:
containers:
- name: api
image: registry/mytv-api:latest
ports:
- containerPort: 3000
env:
- name: NODE_ENV
value: production
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: mytv-secrets
key: database-url
resources:
requests:
cpu: 250m
memory: 512Mi
limits:
cpu: 1000m
memory: 1Gi
livenessProbe:
httpGet:
path: /api/v2/health/live
port: 3000
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /api/v2/health/live
port: 3000
initialDelaySeconds: 5
periodSeconds: 5

Service

apiVersion: v1
kind: Service
metadata:
name: mytv-api
namespace: mytv
spec:
type: ClusterIP
selector:
app: mytv-api
ports:
- port: 80
targetPort: 3000

HPA (Horizontal Pod Autoscaler)

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: mytv-api-hpa
namespace: mytv
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: mytv-api
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80

Ingress

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: mytv-api-ingress
namespace: mytv
annotations:
kubernetes.io/ingress.class: nginx
cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
tls:
- hosts:
- api.mytelevision.app
secretName: mytv-api-tls
rules:
- host: api.mytelevision.app
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: mytv-api
port:
number: 80

Manifestes de base

FichierDescription
namespace.yamlNamespace dedie mytv
configmap.yamlConfiguration non-sensible
secrets.yaml.exampleTemplate pour les secrets
deployment.yamlDeploiement de l'API (2 replicas)
service.yamlService ClusterIP + Headless
ingress.yamlIngress NGINX avec TLS
hpa.yamlAuto-scaling horizontal
pdb.yamlPod Disruption Budget
serviceaccount.yamlServiceAccount + RBAC
networkpolicy.yamlPolitiques reseau

Securite Kubernetes

Pod Security

  • runAsNonRoot: true
  • runAsUser: 1001
  • readOnlyRootFilesystem: true
  • allowPrivilegeEscalation: false

Network Policies

  • Deny all par defaut
  • Autorisation explicite vers PostgreSQL/Redis
  • Autorisation HTTPS sortant pour APIs externes

RBAC

  • ServiceAccount dedie
  • Permissions minimales (lecture ConfigMaps/Secrets)

Secrets Kubernetes

# Creer secrets
kubectl create secret generic mytv-secrets \
--from-literal=JWT_SECRET=xxx \
--from-literal=DATABASE_URL=xxx \
-n mytv

# Depuis fichier
kubectl create secret generic mytv-secrets \
--from-env-file=.env.production \
-n mytv

Helm Chart

Installation

# Ajouter les dependances
cd helm/mytv-api
helm dependency update

# Installation (dev)
helm install mytv-api . \
--namespace mytv \
--create-namespace \
-f values.yaml \
--set existingSecret=mytv-api-secrets

# Installation (production)
helm install mytv-api . \
--namespace mytv \
--create-namespace \
-f values.yaml \
-f values-prod.yaml

Valeurs configurables

ParametreDescriptionDefaut
replicaCountNombre de replicas2
image.repositoryImage Dockermytv/api
image.tagTag de l'imageChart.appVersion
resources.requests.cpuCPU demande100m
resources.requests.memoryMemoire demandee256Mi
resources.limits.cpuCPU limite500m
resources.limits.memoryMemoire limite512Mi
autoscaling.enabledActiver HPAtrue
autoscaling.minReplicasMin replicas2
autoscaling.maxReplicasMax replicas10
ingress.enabledActiver Ingresstrue
ingress.hosts[0].hostHostnameapi.mytelevision.app

Mise a jour

# Mettre a jour l'application
helm upgrade mytv-api . \
--namespace mytv \
--reuse-values \
--set image.tag=v2.1.0

Rolling Update

# Mettre a jour l'image
kubectl set image deployment/mytv-api api=registry/mytv-api:v2.1.0 -n mytv

# Verifier le status
kubectl rollout status deployment/mytv-api -n mytv

# Rollback si probleme
kubectl rollout undo deployment/mytv-api -n mytv

# Historique
kubectl rollout history deployment/mytv-api -n mytv

Infrastructure Terraform

Architecture Cloud (AWS)

┌─────────────────────────────────────────────────────────────────────────────────┐
│ AWS Cloud │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ VPC (10.0.0.0/16) │ │
│ │ ┌──────────────────────────────────────────────────────────────────┐ │ │
│ │ │ Public Subnets: ALB, NAT Gateway │ │ │
│ │ └──────────────────────────────────────────────────────────────────┘ │ │
│ │ ┌──────────────────────────────────────────────────────────────────┐ │ │
│ │ │ Private Subnets: ECS/EKS API Pods (multi-AZ) │ │ │
│ │ └──────────────────────────────────────────────────────────────────┘ │ │
│ │ ┌──────────────────────────────────────────────────────────────────┐ │ │
│ │ │ Data Subnets: RDS PostgreSQL, ElastiCache Redis │ │ │
│ │ └──────────────────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────┘

Modules Terraform

ModuleDescription
networkVPC, Subnets, Security Groups, NAT Gateway
computeECS/EKS, Auto Scaling
databaseRDS PostgreSQL
storageS3/R2, CloudFront
observabilityCloudWatch, Prometheus
securityIAM, Secrets Manager, KMS

Security Groups

Security GroupIngressSource
ALB80, 4430.0.0.0/0
API3000ALB SG
Database5432API SG
Redis6379API SG

Environnements Terraform

EnvironnementNAT GatewayInstancesMulti-AZ RDSDeletion Protection
devSinglet3.microNonNon
stagingSinglet3.smallOuiOui
prodMulti-AZt3.medium+OuiOui

Commandes Terraform

cd iac/environments/dev
terraform init
terraform plan
terraform apply

CI/CD avec Helm

# .github/workflows/deploy.yml
- name: Deploy to Kubernetes
run: |
helm upgrade --install mytv-api ./helm/mytv-api \
--namespace mytv \
--set image.tag=${{ github.sha }}

ArgoCD (GitOps)

# argocd/application.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: mytv-api
spec:
source:
repoURL: https://github.com/XKS-MYTV4JS/mytelevision-restfullapijsv4
path: helm/mytv-api
helm:
valueFiles:
- values.yaml
- values-prod.yaml

Troubleshooting

# Logs d'un pod
kubectl logs <pod-name> -n mytv

# Logs precedents (si crash)
kubectl logs <pod-name> -n mytv --previous

# Shell dans un pod
kubectl exec -it <pod-name> -n mytv -- /bin/sh

# Describe pod
kubectl describe pod <pod-name> -n mytv

# Events du namespace
kubectl get events -n mytv --sort-by='.lastTimestamp'

Commandes utiles

# Kubernetes
kubectl get all -n mytv # Voir toutes les ressources
kubectl logs -f -l app=mytv-api # Logs en temps reel
kubectl describe pod <pod-name> # Details d'un pod
kubectl top pods -n mytv # Utilisation ressources

# Helm
helm list -n mytv # Lister les releases
helm history mytv-api -n mytv # Historique
helm rollback mytv-api 1 -n mytv # Rollback
helm template mytv-api . # Previsualiser les manifestes
helm lint . # Valider le chart

# Terraform
terraform init # Initialiser
terraform plan # Previsualiser
terraform apply # Appliquer
terraform destroy # Detruire
terraform state list # Lister les ressources

Bonnes pratiques

Kubernetes / Helm

  1. Secrets : Utiliser External Secrets Operator ou Vault
  2. Resources : Toujours definir requests/limits
  3. Health checks : Configurer liveness/readiness probes
  4. Security : Network Policies + Pod Security

Terraform

  1. State management : Utiliser un backend distant (S3/GCS)
  2. Modules : Reutiliser les modules entre environnements
  3. Variables : Separer configuration sensible (tfvars)
  4. Locking : DynamoDB pour le verrouillage d'etat