deploy-apps
Helm chart flexível para deploy de múltiplas aplicações (Deployment, StatefulSet, CronJob, Job) com suporte a External Secrets e KEDA
About this chart
deploy-apps
Helm chart flexível para deploy de múltiplas aplicações (Deployment, StatefulSet, CronJob, Job) com suporte a External Secrets Operator e KEDA.
Características
- Multi-aplicação: Deploy múltiplas aplicações em um único chart
- Workload Types: Suporte para Deployment, StatefulSet, CronJob e Job
- External Secrets: Integração com External Secrets Operator para gerenciamento seguro de secrets
- Native Secrets: Suporte também para secrets nativos do Kubernetes
- RBAC Flexível: ServiceAccount e RBAC global ou per-app
- Probes: Configuração completa de liveness, readiness e startup probes
- Networking: Service, Ingress e Gateway API (Envoy) configuráveis por aplicação
- Persistence: Suporte a PersistentVolumes, PersistentVolumeClaims e volumeClaimTemplates
- Autoscaling: HorizontalPodAutoscaler para Deployments e StatefulSets
- KEDA: Autoscaling event-driven com suporte a SQS, Redis, Kafka, RabbitMQ, Prometheus e mais
- PodDisruptionBudget: PDB nativo por aplicação (Deployment/StatefulSet), desabilitado por padrão
Pré-requisitos
- Kubernetes >= 1.27
- Helm 3.x
- External Secrets Operator (opcional, apenas se usar external secrets)
- KEDA (opcional, apenas se usar kedaScaling)
Instalação
Adicionar o repositório Helm
helm repo add cloudscript https://charts.cloudscript.com.br
helm repo update
Instalar o chart
helm install my-apps cloudscript/deploy-apps -f values.yaml
Instalar de um arquivo local
helm install my-apps ./deploy-apps -f values.yaml
Estrutura de Configuração
O chart usa uma estrutura baseada em array para definir múltiplas aplicações:
apps:
- name: app-name
enabled: true
type: deployment # deployment, statefulset, cronjob, job
# ... configurações específicas da aplicação
Exemplos
Exemplo 1: Deployment Simples com Ingress
apps:
- name: web-app
enabled: true
type: deployment
replicaCount: 2
image:
repository: nginx
tag: "1.21"
pullPolicy: IfNotPresent
ports:
- name: http
containerPort: 80
protocol: TCP
service:
enabled: true
type: ClusterIP
ports:
- name: http
port: 80
targetPort: http
ingress:
enabled: true
className: nginx
annotations:
cert-manager.io/cluster-issuer: letsencrypt-prod
hosts:
- host: myapp.example.com
paths:
- path: /
pathType: Prefix
portName: http
tls:
- secretName: myapp-tls
hosts:
- myapp.example.com
resources:
limits:
cpu: 500m
memory: 512Mi
requests:
cpu: 250m
memory: 256Mi
livenessProbe:
httpGet:
path: /healthz
port: http
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: http
initialDelaySeconds: 5
periodSeconds: 10
Exemplo 1b: Deployment com Gateway API (Envoy/Envoy Gateway)
Suporte a Gateway API para Envoy, permitindo rules flexíveis: HTTP, HTTPS ou redirect.
gatewayApi:
gatewayClassName: eg
clusterIssuer: letsencrypt-prod
apps:
- name: web-app
enabled: true
type: deployment
replicaCount: 2
image:
repository: nginx
tag: "1.21"
service:
enabled: true
ports:
- name: http
port: 80
targetPort: http
gatewayApi:
enabled: true
gateway:
name: web-app-gateway
listeners:
- name: https-main
hostname: myapp.example.com
secretName: myapp-tls
httpRoutes:
# Redirect HTTP -> HTTPS
- name: redirect
listenerName: http-main
hostnames:
- myapp.example.com
rules:
- type: redirect
requestRedirect:
scheme: https
port: 443
statusCode: 301
# Roteamento HTTPS para o service
- name: main
listenerName: https-main
hostnames:
- myapp.example.com
rules:
- type: http
backendRef:
port: 80
Com mergeGateways: true no EnvoyProxy, todos os Gateways são mesclados no mesmo NLB.
Para usar um Gateway existente em vez de criar um novo:
gatewayApi:
enabled: true
gatewayRef:
name: shared-gateway
namespace: networking
httpRoutes: [...]
Para rotas individuais que precisam apontar para um gateway diferente (ex: gateway compartilhado para domínio externo):
gatewayApi:
enabled: true
gateway:
name: my-app-gateway
listeners:
- name: https-main
hostname: myapp.internal.com
secretName: myapp-tls
httpRoutes:
# Rota que usa o gateway da própria app
- name: main
listenerName: https-main
hostnames:
- myapp.internal.com
rules:
- type: http
backendRef:
port: 80
# Rota que usa um gateway compartilhado externo
- name: external
listenerName: https-external
gatewayRef:
name: shared-external-gateway
hostnames:
- myapp.external.com
rules:
- type: http
backendRef:
port: 80
Exemplo 2: Job com ArgoCD Hooks
Jobs do Kubernetes são deletados após a execução (via ttlSecondsAfterFinished), o que faz o ArgoCD marcá-los como "Missing". Para resolver, use annotations de hook:
apps:
- name: db-migrate
enabled: true
type: job
annotations:
argocd.argoproj.io/hook: PreSync
argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
image:
repository: mycompany/api
tag: v1.0.0
command: ["dotnet", "MyApp.dll", "--db-setup"]
backoffLimit: 0
ttlSecondsAfterFinished: 300
env:
- name: ConnectionStrings__Default
valueFrom:
secretKeyRef:
name: my-secret
key: ConnectionStrings__Default
PreSync: o Job roda antes do deploy principalBeforeHookCreation: o ArgoCD deleta o Job anterior antes de criar um novo no próximo sync
Exemplo 3: CronJob com External Secrets
apps:
- name: backup-job
enabled: true
type: cronjob
schedule: "0 2 * * *" # Todo dia às 2h da manhã
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 1
concurrencyPolicy: Forbid
image:
repository: backup-tool
tag: latest
command: ["/bin/sh"]
args:
- "-c"
- |
echo "Starting backup..."
# Comandos de backup aqui
echo "Backup completed"
secrets:
external:
enabled: true
items:
- name: aws-credentials
secretStoreRef:
name: aws-secret-store
kind: SecretStore
refreshInterval: 1h
data:
- secretKey: AWS_ACCESS_KEY_ID
remoteRef:
key: prod/backup/aws
property: accessKeyId
- secretKey: AWS_SECRET_ACCESS_KEY
remoteRef:
key: prod/backup/aws
property: secretAccessKey
envFrom:
- secretRef:
name: my-apps-backup-job-aws-credentials
resources:
limits:
cpu: 1000m
memory: 1Gi
requests:
cpu: 500m
memory: 512Mi
Exemplo 4: Deployment com PersistentVolume (S3 CSI)
apps:
- name: api
enabled: true
type: deployment
replicaCount: 2
image:
repository: mycompany/api
tag: v1.0.0
persistentVolumes:
enabled: true
items:
- name: s3-data-pv
spec:
capacity:
storage: 2Gi
accessModes:
- ReadWriteMany
mountOptions:
- allow-delete
- region us-east-2
- prefix myapp/
csi:
driver: s3.csi.aws.com
volumeHandle: myapp-s3-volume
volumeAttributes:
bucketName: my-bucket
authenticationSource: pod
persistence:
enabled: true
items:
- name: s3-data
size: 2Gi
accessModes:
- ReadWriteMany
storageClass: ""
volumeName: mycompany-api-api-s3-data-pv
mountPath: /data/s3
Exemplo 5: StatefulSet com Persistence
apps:
- name: database
enabled: true
type: statefulset
replicaCount: 3
image:
repository: postgres
tag: "14-alpine"
serviceName: database-headless
podManagementPolicy: OrderedReady
ports:
- name: postgresql
containerPort: 5432
protocol: TCP
env:
- name: POSTGRES_DB
value: mydb
- name: PGDATA
value: /var/lib/postgresql/data/pgdata
secrets:
native:
enabled: true
items:
- name: db-creds
type: Opaque
stringData:
POSTGRES_USER: admin
POSTGRES_PASSWORD: changeme
envFrom:
- secretRef:
name: my-apps-database-db-creds
livenessProbe:
exec:
command:
- /bin/sh
- -c
- pg_isready -U postgres
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
exec:
command:
- /bin/sh
- -c
- pg_isready -U postgres
initialDelaySeconds: 5
periodSeconds: 10
service:
enabled: true
type: ClusterIP
clusterIP: None # Headless service
ports:
- name: postgresql
port: 5432
targetPort: postgresql
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes:
- ReadWriteOnce
storageClassName: fast-ssd
resources:
requests:
storage: 50Gi
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
resources:
limits:
cpu: 2000m
memory: 4Gi
requests:
cpu: 1000m
memory: 2Gi
Exemplo 6: Multi-App (Deployment + CronJob)
apps:
# Frontend Application with Autoscaling
- name: frontend
enabled: true
type: deployment
# NÃO definir replicaCount quando autoscaling está habilitado
image:
repository: mycompany/frontend
tag: v1.2.3
ports:
- name: http
containerPort: 3000
# Resources são necessários para HPA funcionar
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 512Mi
service:
enabled: true
ports:
- name: http
port: 80
targetPort: 3000
ingress:
enabled: true
className: nginx
hosts:
- host: app.example.com
paths:
- path: /
pathType: Prefix
# Autoscaling habilitado
autoscaling:
enabled: true
minReplicas: 3
maxReplicas: 10
targetCPUUtilizationPercentage: 70
targetMemoryUtilizationPercentage: 80
# Background Job
- name: data-sync
enabled: true
type: cronjob
schedule: "*/30 * * * *" # A cada 30 minutos
image:
repository: mycompany/data-sync
tag: v1.0.0
command: ["python"]
args: ["sync_data.py"]
secrets:
external:
enabled: true
items:
- name: api-keys
secretStoreRef:
name: aws-secret-store
data:
- secretKey: API_KEY
remoteRef:
key: prod/api/keys
property: key
resources:
limits:
cpu: 500m
memory: 512Mi
Exemplo 7: KEDA - Autoscaling Event-Driven
O chart suporta KEDA ScaledObject para autoscaling baseado em eventos (filas SQS, Redis, Kafka, etc.).
KEDA com Redis + SQS + CPU
serviceAccount:
create: true
annotations:
eks.amazonaws.com/role-arn: "arn:aws:iam::123456789:role/my-role"
apps:
- name: api
enabled: true
type: deployment
# NÃO definir replicaCount - KEDA gerencia automaticamente
image:
repository: mycompany/api
tag: v1.0.0
ports:
- name: http
containerPort: 8080
service:
enabled: true
ports:
- name: http
port: 80
targetPort: http
resources:
limits:
cpu: 1
memory: 1Gi
requests:
cpu: 100m
memory: 128Mi
kedaScaling:
enabled: true
minReplicas: 2
maxReplicas: 16
pollingInterval: 60
cooldownPeriod: 300
# TriggerAuthentication - cria automaticamente o recurso
triggerAuthentication:
enabled: true
podIdentity:
provider: aws
secretTargetRef:
- parameter: host
name: my-app-secret
key: REDIS_HOST
- parameter: port
name: my-app-secret
key: REDIS_PORT
- parameter: password
name: my-app-secret
key: REDIS_PASSWORD
triggers:
# CPU e Memory
- type: cpu
metricType: AverageValue
metadata:
value: "800m"
- type: memory
metricType: AverageValue
metadata:
value: "800Mi"
# Redis - useAuth injeta o authenticationRef automaticamente
- type: redis
useAuth: true
metadata:
listName: my-queue
listLength: "50"
enableTLS: "false"
databaseIndex: "0"
# AWS SQS
- type: aws-sqs-queue
useAuth: true
metadata:
queueURL: https://sqs.us-east-1.amazonaws.com/1
Deploy deploy-apps with OpenTenant
Each tenant gets its own release of this chart, with its own namespace, secrets and domain. The builder below already has deploy-apps on a Hetzner server. Change the host, add apps from the marketplace, then copy the generated files. Providers and prices are samples, and nothing here is sent anywhere.
- Pick a serverConnect Hetzner, OVHcloud or AWS. The builder starts on Hetzner, the cheapest sample rate.
- Place the chartdeploy-apps is pinned at v0.4.1 in opentenant.yaml. Drag more apps from the marketplace onto a rack.
- ApplySave opentenant.yaml and main.tf from the console, then run the commands below.
# opentenant.yaml, main.tf and dns.tf come from the builder below opentenant validate opentenant.yaml terraform init && terraform apply