# Service Mesh

> 🕸️ **Microservices Connectivity**: Panduan komprehensif untuk implementasi service mesh dengan Istio, traffic management, dan observability.

***

## 📋 **Daftar Isi**

### **🌐 Service Mesh Fundamentals**

* [What is Service Mesh](#what-is-service-mesh)
* [Service Mesh Architecture](#service-mesh-architecture)
* [Benefits of Service Mesh](#benefits-of-service-mesh)
* [When to Use Service Mesh](#when-to-use-service-mesh)

### **🚀 Istio Installation**

* [Istio Overview](#istio-overview)
* [Installation Methods](#installation-methods)
* [Configuration Profiles](#configuration-profiles)
* [Post-Installation Setup](#post-installation-setup)

### **🔧 Traffic Management**

* [Traffic Routing](#traffic-routing)
* [Load Balancing](#load-balancing)
* [Circuit Breaking](#circuit-breaking)
* [Timeouts and Retries](#timeouts-and-retries)
* [Mirroring](#mirroring)
* [Fault Injection](#fault-injection)

### **🔒 Security**

* [Mutual TLS (mTLS)](#mutual-tls-mtls)
* [Authentication Policies](#authentication-policies)
* [Authorization Policies](#authorization-policies)
* [Certificate Management](#certificate-management)
* [Secure Ingress](#secure-ingress)
* [Secure Egress](#secure-egress)

### **📊 Observability**

* [Telemetry](#telemetry)
* [Metrics](#metrics)
* [Distributed Tracing](#distributed-tracing)
* [Logging](#logging)
* [Visualization](#visualization)

### **🎯 Advanced Features**

* [Canary Deployments](#canary-deployments)
* [A/B Testing](#ab-testing)
* [Blue-Green Deployments](#blue-green-deployments)
* [Chaos Engineering](#chaos-engineering)
* [Multi-Cluster Mesh](#multi-cluster-mesh)

***

## 🌐 **Service Mesh Fundamentals**

### What is Service Mesh

**📖 Konsep Dasar** Service mesh adalah dedicated infrastructure layer untuk handling service-to-service communication dalam microservices architecture. Istio sebagai salah satu implementasi paling populer menyediakan:

* **Traffic Management**: Routing, load balancing, fault injection
* **Security**: mTLS, authentication, authorization
* **Observability**: Metrics, tracing, logging
* **Policy Enforcement**: Access control, rate limiting

**🏗️ Service Mesh Components**

```yaml
# Istio data plane components
Data Plane:
├── Envoy Proxies (Sidecars)
│   ├── Traffic Management
│   ├── Security
│   └── Observability
└── Application Containers

# Istio control plane components
Control Plane:
├── Pilot (Traffic Management)
├── Citadel (Security)
├── Galley (Configuration)
└── Mixer (Policy & Telemetry - Legacy)
```

### Service Mesh Architecture

**🔧 Istio Architecture Overview**

```
┌─────────────────────────────────────────────────────────┐
│                    Control Plane                         │
├─────────────────┬─────────────────┬─────────────────────┤
│     Pilot       │    Citadel      │      Galley          │
│ (Traffic Mgmt)   │  (Security)     │ (Configuration)      │
└─────────────────┴─────────────────┴─────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────┐
│                   Data Plane                             │
├─────────────────┬─────────────────┬─────────────────────┤
│   Pod A         │   Pod B         │      Pod C           │
│ ┌─────────────┐ │ ┌─────────────┐ │ ┌─────────────────┐ │
│ │   App A     │ │ │   App B     │ │ │      App C       │ │
│ └─────────────┘ │ └─────────────┘ │ └─────────────────┘ │
│ ┌─────────────┐ │ ┌─────────────┐ │ ┌─────────────────┐ │
│ │ Envoy Proxy │ │ │ Envoy Proxy │ │ │   Envoy Proxy   │ │
│ └─────────────┘ │ └─────────────┘ │ └─────────────────┘ │
└─────────────────┴─────────────────┴─────────────────────┘
                           │
                           ▼
                  ┌───────────────┐
                  │  External     │
                  │  Services     │
                  └───────────────┘
```

### Benefits of Service Mesh

**🎯 Keuntungan Utama Service Mesh**

1. **Traffic Control**
   * Advanced routing capabilities
   * Load balancing algorithms
   * Traffic shifting and splitting
   * Circuit breaking and timeouts
2. **Security**
   * Automatic mTLS encryption
   * Fine-grained access control
   * Identity-based authentication
   * Policy enforcement
3. **Observability**
   * Distributed tracing
   * Rich metrics collection
   * Service-level monitoring
   * Traffic flow visualization
4. **Resilience**
   * Automatic retries
   * Fault injection for testing
   * Traffic mirroring
   * Graceful degradation

### When to Use Service Mesh

**📋 Use Cases**

| Scenario                | Service Mesh Benefits                | Recommended |
| ----------------------- | ------------------------------------ | ----------- |
| **Large Microservices** | Complex traffic management, security | ✅ Yes       |
| **Multi-Cluster Apps**  | Cross-cluster communication          | ✅ Yes       |
| **Strict Security**     | mTLS, fine-grained policies          | ✅ Yes       |
| **Complex Routing**     | A/B testing, canary deployments      | ✅ Yes       |
| **Small Apps**          | Overhead complexity                  | ❌ No        |
| **Monolith**            | Limited benefits                     | ❌ No        |

***

## 🚀 **Istio Installation**

### Istio Overview

**📖 Istio Versions**

* **Latest Stable**: 1.19.0
* **LTS Versions**: 1.18.x, 1.17.x
* **Compatibility**: Kubernetes 1.25+ supported

**🔧 Installation Methods**

1. **istioctl CLI** - Recommended for production
2. **Helm Charts** - Custom configuration
3. **Operator** - Kubernetes native deployment
4. **Istioctl Operator** - Automated management

### Installation Methods

**🚀 Installation dengan istioctl**

```bash
# Download istioctl
curl -L https://istio.io/downloadIstio | ISTIO_VERSION=1.19.0 TARGET_ARCH=x86_64 sh -
cd istio-1.19.0
export PATH=$PWD/bin:$PATH

# Verify installation
istioctl version

# Pre-check cluster compatibility
istioctl x precheck

# Install Istio
istioctl install --set profile=demo -y

# Verify installation
kubectl get pods -n istio-system
kubectl get svc -n istio-system
```

**🔧 Installation dengan Helm**

```bash
# Add Istio Helm repository
helm repo add istio https://istio-release.storage.googleapis.com/charts
helm repo update

# Create namespace
kubectl create namespace istio-system

# Install Istio base
helm install istio-base istio/base -n istio-system --wait

# Install Istio discovery
helm install istiod istio/istiod -n istio-system --wait

# Install Istio gateway (optional)
kubectl create namespace istio-ingress
helm install istio-ingress istio/gateway -n istio-ingress --wait
```

### Configuration Profiles

**📋 Istio Configuration Profiles**

| Profile   | Description                | Use Case                  |
| --------- | -------------------------- | ------------------------- |
| `minimal` | Minimal components         | Small deployments         |
| `default` | Recommended for production | Most production workloads |
| `demo`    | Complete with telemetry    | Demo and testing          |
| `preview` | Experimental features      | Testing new features      |

**🔧 Custom Profile Configuration**

```yaml
# custom-profile.yaml
apiVersion: install.istio.io/v1alpha1
kind: IstioOperator
metadata:
  name: production-profile
  namespace: istio-system
spec:
  profile: default
  values:
    global:
      meshID: mesh1
      multiCluster:
        enabled: true
        clusterName: cluster1
      network: network1
  components:
    pilot:
      k8s:
        resources:
          requests:
            cpu: 500m
            memory: 2Gi
        hpaSpec:
          minReplicas: 2
          maxReplicas: 5
    ingressGateways:
    - name: istio-ingressgateway
      enabled: true
      k8s:
        service:
          type: LoadBalancer
          ports:
          - port: 80
            targetPort: 8080
            name: http2
          - port: 443
            targetPort: 8443
            name: https
    egressGateways:
    - name: istio-egressgateway
      enabled: true
    telemetry:
      v2:
        enabled: true

# Apply custom profile
istioctl install -f custom-profile.yaml -y
```

### Post-Installation Setup

**🔧 Automatic Sidecar Injection**

```bash
# Enable automatic injection for namespace
kubectl label namespace production istio-injection=enabled

# Verify automatic injection
kubectl get namespace production -L istio-injection

# Deploy sample application
kubectl apply -f - <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: httpbin
  namespace: production
spec:
  replicas: 1
  selector:
    matchLabels:
      app: httpbin
      version: v1
  template:
    metadata:
      labels:
        app: httpbin
        version: v1
    spec:
      containers:
      - name: httpbin
        image: kennethreitz/httpbin
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: httpbin
  namespace: production
  labels:
    app: httpbin
spec:
  ports:
  - name: http
    port: 8000
    targetPort: 80
  selector:
    app: httpbin
EOF

# Verify sidecar injection
kubectl get pod -n production -l app=httpbin -o yaml | grep -A 20 "containers:"
```

**🔍 Verify Installation**

```bash
# Check control plane status
istioctl proxy-status

# Check control plane configuration
istioctl proxy-config clusters deployment/httpbin -n production

# Test service connectivity
kubectl exec -it $(kubectl get pod -n production -l app=httpbin -o jsonpath='{.items[0].metadata.name}') -n production -- curl http://localhost:8000/ip

# Check metrics
kubectl exec -it $(kubectl get pod -n production -l app=httpbin -o jsonpath='{.items[0].metadata.name}') -n production -c istio-proxy -- curl localhost:15000/stats/prometheus | grep http
```

***

## 🔧 **Traffic Management**

### Traffic Routing

**🛣️ Virtual Service Configuration**

```yaml
# Basic routing configuration
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: httpbin-route
  namespace: production
spec:
  hosts:
  - httpbin.production.svc.cluster.local
  gateways:
  - mesh
  http:
  - match:
    - uri:
        prefix: /
    route:
    - destination:
        host: httpbin.production.svc.cluster.local
        port:
          number: 8000
    timeout: 3s
    retries:
      attempts: 3
      perTryTimeout: 2s

# Advanced routing with version-based traffic splitting
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: app-route
  namespace: production
spec:
  hosts:
  - app.production.svc.cluster.local
  http:
  - match:
    - headers:
        user-group:
          exact: beta-testers
    route:
    - destination:
        host: app.production.svc.cluster.local
        subset: v2
      weight: 100
  - route:
    - destination:
        host: app.production.svc.cluster.local
        subset: v1
      weight: 90
    - destination:
        host: app.production.svc.cluster.local
        subset: v2
      weight: 10

# Destination rule for subset configuration
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: app-destination
  namespace: production
spec:
  host: app.production.svc.cluster.local
  trafficPolicy:
    loadBalancer:
      simple: LEAST_CONN
    connectionPool:
      tcp:
        maxConnections: 100
      http:
        http1MaxPendingRequests: 50
        maxRequestsPerConnection: 10
    circuitBreaker:
      consecutiveErrors: 3
      interval: 30s
      baseEjectionTime: 30s
  subsets:
  - name: v1
    labels:
      version: v1
    trafficPolicy:
      loadBalancer:
        simple: ROUND_ROBIN
  - name: v2
    labels:
      version: v2
    trafficPolicy:
      loadBalancer:
        simple: RANDOM
```

### Load Balancing

**⚖️ Load Balancing Configuration**

```yaml
# Various load balancing strategies
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: load-balancing-example
  namespace: production
spec:
  host: app.production.svc.cluster.local
  trafficPolicy:
    loadBalancer:
      simple: LEAST_CONN  # Options: ROUND_ROBIN, LEAST_CONN, RANDOM, PASSTHROUGH
    connectionPool:
      tcp:
        maxConnections: 100
        connectTimeout: 30s
        keepAlive:
          time: 7200s
          interval: 75s
      http:
        http1MaxPendingRequests: 50
        maxRequestsPerConnection: 10
        maxRetries: 3
    outlierDetection:
      consecutiveErrors: 3
      interval: 30s
      baseEjectionTime: 30s
      maxEjectionPercent: 50
      minHealthPercent: 50

# Locality-aware load balancing
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: locality-lb
  namespace: production
spec:
  host: app.production.svc.cluster.local
  trafficPolicy:
    loadBalancer:
      localityLbSetting:
        enabled: true
        failover:
        - from: us-west-2
          to: us-west-1,us-east-1
        - from: us-west-1
          to: us-west-2,us-east-1
        - from: us-east-1
          to: us-west-2,us-west-1
    connectionPool:
      tcp:
        maxConnections: 100
      http:
        http1MaxPendingRequests: 50
```

### Circuit Breaking

**🔌 Circuit Breaking Configuration**

```yaml
# Circuit breaking with connection pool settings
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: circuit-breaker-example
  namespace: production
spec:
  host: api.production.svc.cluster.local
  trafficPolicy:
    connectionPool:
      tcp:
        maxConnections: 100
        connectTimeout: 30s
      http:
        http1MaxPendingRequests: 50
        maxRequestsPerConnection: 10
        maxRetries: 3
    circuitBreaker:
      consecutiveErrors: 3
      interval: 30s
      baseEjectionTime: 30s
      maxEjectionPercent: 50
      minHealthPercent: 50
    outlierDetection:
      consecutiveGatewayErrors: 5
      interval: 30s
      baseEjectionTime: 30s
      maxEjectionPercent: 50
      minHealthPercent: 40

# Advanced circuit breaking with custom settings
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: advanced-circuit-breaker
  namespace: production
spec:
  host: critical-api.production.svc.cluster.local
  trafficPolicy:
    connectionPool:
      tcp:
        maxConnections: 50
        connectTimeout: 10s
        keepAlive:
          time: 300s
          interval: 30s
      http:
        http1MaxPendingRequests: 20
        http2MaxRequests: 100
        maxRequestsPerConnection: 5
        maxRetries: 2
        idleTimeout: 300s
        h2UpgradePolicy: UPGRADE
    circuitBreaker:
      consecutiveErrors: 2
      interval: 15s
      baseEjectionTime: 60s
      maxEjectionPercent: 80
      minHealthPercent: 30
    outlierDetection:
      consecutive5xxErrors: 2
      interval: 15s
      baseEjectionTime: 60s
      maxEjectionPercent: 80
      minHealthPercent: 30
```

### Timeouts and Retries

**⏱️ Timeout and Retry Configuration**

```yaml
# Virtual service with timeouts and retries
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: timeout-retry-example
  namespace: production
spec:
  hosts:
  - api.production.svc.cluster.local
  http:
  - match:
    - uri:
        prefix: /fast
    route:
    - destination:
        host: fast-api.production.svc.cluster.local
    timeout: 2s
    retries:
      attempts: 3
      perTryTimeout: 1s
      retryOn: gateway-error,connect-failure,refused-stream
  - match:
    - uri:
        prefix: /slow
    route:
    - destination:
        host: slow-api.production.svc.cluster.local
    timeout: 10s
    retries:
      attempts: 2
      perTryTimeout: 5s
      retryOn: 5xx,gateway-error,connect-failure,refused-stream
  - match:
    - uri:
        prefix: /critical
    fault:
      delay:
        percentage:
          value: 0.1
        fixedDelay: 5s
    route:
    - destination:
        host: critical-api.production.svc.cluster.local
    timeout: 15s
    retries:
      attempts: 5
      perTryTimeout: 3s
      retryOn: 5xx,gateway-error,connect-failure,refused-stream

# Global retry policy
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: global-retry-policy
  namespace: production
spec:
  host: "*.production.svc.cluster.local"
  trafficPolicy:
    connectionPool:
      http:
        maxRetries: 3
        retryOn: gateway-error,connect-failure,refused-stream
    circuitBreaker:
      consecutiveErrors: 3
      interval: 30s
      baseEjectionTime: 30s
```

### Mirroring

**🪞 Traffic Mirroring Configuration**

```yaml
# Traffic mirroring for testing
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: traffic-mirroring
  namespace: production
spec:
  hosts:
  - app.production.svc.cluster.local
  http:
  - route:
    - destination:
        host: app.production.svc.cluster.local
        subset: v1
      weight: 100
    mirror:
      host: app.production.svc.cluster.local
      subset: v2
    mirrorPercentage:
      value: 100

# Selective mirroring based on headers
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: selective-mirroring
  namespace: production
spec:
  hosts:
  - api.production.svc.cluster.local
  http:
  - match:
    - headers:
        x-test-user:
          exact: "true"
    route:
    - destination:
        host: api.production.svc.cluster.local
        subset: v2
      weight: 100
    mirror:
      host: api.production.svc.cluster.local
      subset: v3
    mirrorPercentage:
      value: 100
  - route:
    - destination:
        host: api.production.svc.cluster.local
        subset: v1
      weight: 100
```

### Fault Injection

**💥 Fault Injection for Testing**

```yaml
# HTTP fault injection
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: fault-injection
  namespace: production
spec:
  hosts:
  - app.production.svc.cluster.local
  http:
  - match:
    - uri:
        prefix: /api/v1/users
    fault:
      delay:
        percentage:
          value: 0.1  # 10% of requests
        fixedDelay: 5s
    route:
    - destination:
        host: app.production.svc.cluster.local
  - match:
    - uri:
        prefix: /api/v1/orders
    fault:
      abort:
        percentage:
          value: 0.05  # 5% of requests
        httpStatus: 503
    route:
    - destination:
        host: app.production.svc.cluster.local
  - match:
    - headers:
          x-chaos-testing:
            exact: "enabled"
    fault:
      delay:
        percentage:
          value: 1.0  # 100% for testing
        fixedDelay: 2s
      abort:
        percentage:
          value: 0.1
        httpStatus: 500
    route:
    - destination:
        host: app.production.svc.cluster.local

# TCP fault injection (for non-HTTP services)
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: tcp-fault-injection
  namespace: production
spec:
  hosts:
  - database.production.svc.cluster.local
  tcp:
  - fault:
      delay:
        percentage:
          value: 0.05
        fixedDelay: 1s
    route:
    - destination:
        host: database.production.svc.cluster.local
        port:
          number: 5432
```

***

## 🔒 **Security**

### Mutual TLS (mTLS)

**🔐 mTLS Configuration**

```yaml
# Enable mTLS for entire namespace
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: default
  namespace: production
spec:
  mtls:
    mode: STRICT  # Options: DISABLE, PERMISSIVE, STRICT

# mTLS per service
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: app-mtls
  namespace: production
spec:
  selector:
    matchLabels:
      app: secure-app
  mtls:
    mode: STRICT

# Destination rule for mTLS
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: client-mtls
  namespace: production
spec:
  host: api.production.svc.cluster.local
  trafficPolicy:
    tls:
      mode: ISTIO_MUTUAL  # Options: DISABLE, SIMPLE, MUTUAL, ISTIO_MUTUAL
    portLevelSettings:
    - port:
        number: 8443
      tls:
        mode: SIMPLE
        caCertificates: /etc/ssl/certs/ca-certificates.crt
        clientCertificate: /etc/certs/tls.crt
        privateKey: /etc/certs/tls.key
        sni: api.production.svc.cluster.local
```

### Authentication Policies

**🔑 Authentication Configuration**

```yaml
# JWT authentication policy
apiVersion: security.istio.io/v1beta1
kind: RequestAuthentication
metadata:
  name: jwt-auth
  namespace: production
spec:
  selector:
    matchLabels:
      app: api-gateway
  jwtRules:
  - issuer: "https://auth.example.com"
    audiences:
    - "api.example.com"
    jwksUri: "https://auth.example.com/.well-known/jwks.json"
    forwardOriginalToken: true
    fromHeaders:
    - name: x-jwt-token
    fromParams:
    - access_token

# OAuth2 authentication
apiVersion: security.istio.io/v1beta1
kind: RequestAuthentication
metadata:
  name: oauth-auth
  namespace: production
spec:
  selector:
    matchLabels:
      app: web-frontend
  jwtRules:
  - issuer: "https://oauth.example.com"
    audiences:
    - "web.example.com"
    jwksUri: "https://oauth.example.com/.well-known/jwks.json"
    outputPayloadToHeader: x-jwt-claims

# Multiple authentication methods
apiVersion: security.istio.io/v1beta1
kind: RequestAuthentication
metadata:
  name: multi-auth
  namespace: production
spec:
  selector:
    matchLabels:
      app: secure-api
  jwtRules:
  - issuer: "https://auth.example.com"
    audiences:
    - "api.example.com"
    jwksUri: "https://auth.example.com/.well-known/jwks.json"
  - issuer: "https://sso.example.com"
    audiences:
    - "api.example.com"
    jwksUri: "https://sso.example.com/.well-known/jwks.json"
    fromHeaders:
    - name: x-sso-token
```

### Authorization Policies

**🛡️ Authorization Configuration**

```yaml
# Allow all requests within namespace
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: allow-all
  namespace: production
spec:
  selector:
    matchLabels:
      app: public-api
  action: ALLOW
  rules:
  - {}

# Deny all requests by default
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: deny-all
  namespace: production
spec:
  {}
  action: DENY

# Specific authorization rules
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: api-access-policy
  namespace: production
spec:
  selector:
    matchLabels:
      app: secure-api
  action: ALLOW
  rules:
  - from:
    - source:
        principals: ["cluster.local/ns/production/sa/frontend"]
  - to:
    - operation:
        methods: ["GET", "POST"]
        paths: ["/api/v1/*"]
  - when:
    - key: request.auth.claims[role]
      values: ["user", "admin"]

# Role-based access control
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: rbac-policy
  namespace: production
spec:
  action: ALLOW
  rules:
  - from:
    - source:
        requestPrincipals: ["https://auth.example.com/*"]
  - when:
    - key: request.auth.claims[role]
      values: ["admin"]
    to:
    - operation:
        methods: ["GET", "POST", "PUT", "DELETE"]
  - from:
    - source:
        requestPrincipals: ["https://auth.example.com/*"]
  - when:
    - key: request.auth.claims[role]
      values: ["user"]
    to:
    - operation:
        methods: ["GET"]
        paths: ["/api/v1/public/*"]
```

### Certificate Management

**🔐 Certificate Rotation and Management**

```yaml
# Custom certificate configuration
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: custom-cert
  namespace: production
spec:
  selector:
    matchLabels:
      app: secure-app
  mtls:
    mode: STRICT

---
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
  name: istio-gateway-cert
  namespace: istio-system
spec:
  secretName: istio-ingressgateway-certs
  dnsNames:
  - api.example.com
  - "*.api.example.com"
  issuerRef:
    name: letsencrypt-prod
    kind: ClusterIssuer
  duration: 2160h  # 90 days
  renewBefore: 360h  # 15 days before expiration

# Certificate rotation configuration
apiVersion: v1
kind: ConfigMap
metadata:
  name: istio-citadel-configuration
  namespace: istio-system
data:
  config.yaml: |
    default:
      # Certificate rotation interval
      selfsignedcacert: true
      trustdomain: example.com
      workflow:
        rootcacert:
          # CA certificate valid for 10 years
          ttl: 87600h
        intermediatecacert:
          # Intermediate certificate valid for 1 year
          ttl: 8760h
        workloadcert:
          # Workload certificate valid for 24 hours
          ttl: 24h
        workloaddsr:
          # DSR valid for 1 hour
          ttl: 1h
```

### Secure Ingress

**🔒 Secure Ingress Gateway Configuration**

```yaml
# Secure ingress gateway
apiVersion: networking.istio.io/v1beta1
kind: Gateway
metadata:
  name: secure-gateway
  namespace: istio-system
spec:
  selector:
    istio: ingressgateway
  servers:
  - port:
      number: 80
      name: http
      protocol: HTTP
    hosts:
    - "example.com"
    tls:
      httpsRedirect: true  # Redirect HTTP to HTTPS
  - port:
      number: 443
      name: https
      protocol: HTTPS
    tls:
      mode: SIMPLE
      credentialName: istio-ingressgateway-certs
      minProtocolVersion: TLSV1_2
      cipherSuites:
      - "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
      - "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"
      - "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256"
    hosts:
    - "example.com"
    - "*.example.com"

---
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: secure-ingress
  namespace: istio-system
spec:
  hosts:
  - "example.com"
  gateways:
  - secure-gateway
  http:
  - match:
    - uri:
        prefix: /
    route:
    - destination:
        host: web-app.production.svc.cluster.local
        port:
          number: 8080
    corsPolicy:
      allowOrigins:
      - exact: "https://app.example.com"
      - prefix: "https://"
      allowMethods:
      - POST
      - GET
      - OPTIONS
      - PUT
      - DELETE
      allowHeaders:
      - "*"
      maxAge: "24h"
```

### Secure Egress

**🔒 Secure Egress Configuration**

```yaml
# Egress gateway for external services
apiVersion: networking.istio.io/v1beta1
kind: Gateway
metadata:
  name: egressgateway
  namespace: istio-system
spec:
  selector:
    istio: egressgateway
  servers:
  - port:
      number: 443
      name: https
      protocol: HTTPS
    hosts:
    - "external-api.example.com"
    tls:
      mode: MUTUAL
      credentialName: egressgateway-cert

---
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: egressgateway-for-external-api
  namespace: istio-system
spec:
  host: istio-egressgateway.istio-system.svc.cluster.local
  subsets:
  - name: external-api
    trafficPolicy:
      loadBalancer:
        simple: ROUND_ROBIN
      portLevelSettings:
      - port:
          number: 443
        tls:
          mode: ISTIO_MUTUAL
          sni: external-api.example.com

---
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: external-api-through-egressgateway
  namespace: production
spec:
  hosts:
  - external-api.example.com
  gateways:
  - mesh
  - egressgateway
  tcp:
  - match:
    - port: 443
    route:
    - destination:
        host: istio-egressgateway.istio-system.svc.cluster.local
        subset: external-api
        port:
          number: 443
    fault:
      delay:
        percentage:
          value: 0.1
        fixedDelay: 5s
```

***

## 📊 **Observability**

### Telemetry

**📈 Telemetry Configuration**

```yaml
# Istio telemetry configuration (v2)
apiVersion: v1
kind: ConfigMap
metadata:
  name: istio-telemetry
  namespace: istio-system
data:
  mesh: |-
    defaultConfig:
      # Enable telemetry
      telemetry:
        v2:
          enabled: true
      # Enable access logging
      accessLogEncoding: JSON
      accessLogFile: /dev/stdout
      accessLogFormat: |
        {
          "start_time": "%START_TIME%",
          "method": "%REQ(:METHOD)%",
          "path": "%REQ(X-ENVOY-ORIGINAL-PATH?:PATH)%",
          "protocol": "%PROTOCOL%",
          "response_code": "%RESPONSE_CODE%",
          "response_flags": "%RESPONSE_FLAGS%",
          "response_code_details": "%RESPONSE_CODE_DETAILS%",
          "connection_termination_details": "%CONNECTION_TERMINATION_DETAILS%",
          "upstream_transport_failure_reason": "%UPSTREAM_TRANSPORT_FAILURE_REASON%",
          "bytes_received": "%BYTES_RECEIVED%",
          "bytes_sent": "%BYTES_SENT%",
          "duration": "%DURATION%",
          "upstream_service_time": "%REQ(X-ENVOY-UPSTREAM-SERVICE-TIME)%",
          "x_forwarded_for": "%REQ(X-FORWARDED-FOR)%",
          "user_agent": "%REQ(USER-AGENT)%",
          "request_id": "%REQ(X-REQUEST-ID)%",
          "authority": "%REQ(:AUTHORITY)%",
          "upstream_host": "%UPSTREAM_HOST%",
          "upstream_cluster": "%UPSTREAM_CLUSTER%",
          "upstream_local_address": "%UPSTREAM_LOCAL_ADDRESS%",
          "downstream_local_address": "%DOWNSTREAM_LOCAL_ADDRESS%",
          "downstream_remote_address": "%DOWNSTREAM_REMOTE_ADDRESS%",
          "requested_server_name": "%REQUESTED_SERVER_NAME%",
          "route_name": "%ROUTE_NAME%"
        }

# Custom telemetry provider
apiVersion: telemetry.istio.io/v1alpha1
kind: Telemetry
metadata:
  name: custom-telemetry
  namespace: istio-system
spec:
  providers:
  - name: prometheus
    prometheus:
  - name: stackdriver
    stackdriver:
  - name: openTelemetry
    openTelemetry:
      port: 4317
      service:
        name: otel-collector
        namespace: monitoring
```

### Metrics

**📊 Prometheus Metrics Configuration**

```yaml
# Prometheus Istio scrape configuration
apiVersion: v1
kind: ConfigMap
metadata:
  name: prometheus-config
  namespace: monitoring
data:
  prometheus.yml: |
    global:
      scrape_interval: 15s
      evaluation_interval: 15s

    scrape_configs:
    # Istio control plane metrics
    - job_name: 'istio-mesh'
      kubernetes_sd_configs:
      - role: endpoints
        namespaces:
          names:
          - istio-system
      relabel_configs:
      - source_labels: [__meta_kubernetes_service_name, __meta_kubernetes_endpoint_port_name]
        action: keep
        regex: istio-telemetry;http-monitoring
      - source_labels: [__meta_kubernetes_endpoint_address_target_name, __meta_kubernetes_endpoint_port_name]
        target_label: instance
        replacement: ${1}:${2}

    # Istio data plane metrics
    - job_name: 'istio-envoy'
      kubernetes_sd_configs:
      - role: pod
        namespaces:
          names:
          - istio-system
          - production
      relabel_configs:
      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
        action: keep
        regex: true
      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
        action: replace
        target_label: __metrics_path__
        regex: (.+)
      - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
        action: replace
        regex: ([^:]+)(?::\d+)?;(\d+)
        replacement: $1:$2
        target_label: __address__
      - action: labelmap
        regex: __meta_kubernetes_pod_label_(.+)

# Istio metrics configuration
apiVersion: v1
kind: ConfigMap
metadata:
  name: istio-metrics
  namespace: istio-system
data:
  mesh: |-
    defaultConfig:
      # Enable metrics
      proxyStatsMatcher:
        inclusionRegexps:
        - ".*"
        - "http_.*"
        - "tcp_.*"
        - "mysql.*"
        - "postgres.*"
        - "redis.*"
        - "mongodb.*"
      inclusionPrefixes:
        - "outbound"
        - "inbound"
      exclusionSuffixes:
        - ".debug"
        - ".drainer"

# Custom metrics configuration
apiVersion: v1
kind: ConfigMap
metadata:
  name: custom-metrics
  namespace: istio-system
data:
  custom_metrics.yaml: |
    # Define custom metrics for business logic
    metrics:
    - name: "business_transactions_total"
      kind: "COUNTER"
      description: "Total number of business transactions"
    - name: "business_transaction_duration"
      kind: "HISTOGRAM"
      description: "Business transaction duration histogram"
      buckets: [0.1, 0.5, 1.0, 2.5, 5.0, 10.0]
    - name: "business_errors_total"
      kind: "COUNTER"
      description: "Total number of business errors"
```

### Distributed Tracing

**🔍 Jaeger Tracing Configuration**

```yaml
# Jaeger installation for Istio
apiVersion: v1
kind: ConfigMap
metadata:
  name: istio-tracing
  namespace: istio-system
data:
  # Jaeger configuration
  collector:
    zipkin:
      host: jaeger-collector.istio-system
      port: 9411

# Jaeger deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: jaeger
  namespace: istio-system
spec:
  replicas: 1
  selector:
    matchLabels:
      app: jaeger
  template:
    metadata:
      labels:
        app: jaeger
    spec:
      containers:
      - name: jaeger
        image: jaegertracing/all-in-one:latest
        env:
        - name: COLLECTOR_ZIPKIN_HOST_PORT
          value: ":9411"
        ports:
        - containerPort: 5775
        - containerPort: 6831
        - containerPort: 6832
        - containerPort: 5778
        - containerPort: 16686
        - containerPort: 14250
        - containerPort: 14268
        - containerPort: 14269
        - containerPort: 9411
        resources:
          requests:
            cpu: 200m
            memory: 500Mi
          limits:
            cpu: 500m
            memory: 1Gi

---
apiVersion: v1
kind: Service
metadata:
  name: jaeger-query
  namespace: istio-system
  labels:
    app: jaeger
spec:
  type: ClusterIP
  ports:
  - name: query
    port: 16686
    targetPort: 16686
  selector:
    app: jaeger

---
apiVersion: v1
kind: Service
metadata:
  name: jaeger-collector
  namespace: istio-system
  labels:
    app: jaeger
spec:
  type: ClusterIP
  ports:
  - name: jaeger-collector-zipkin
    port: 9411
    targetPort: 9411
  - name: jaeger-collector-http
    port: 14268
    targetPort: 14268
  selector:
    app: jaeger

# Istio tracing configuration
apiVersion: v1
kind: ConfigMap
metadata:
  name: istio-sidecar-injector
  namespace: istio-system
data:
  config: |
    tracing:
      sampling: 100.0
      custom_tags:
        request_id:
          header:
            name: x-request-id
          literal:
            empty_value: "no-request-id"
```

### Logging

**📝 Comprehensive Logging Configuration**

```yaml
# Fluent Bit for Istio logging
apiVersion: v1
kind: ConfigMap
metadata:
  name: fluent-bit-config
  namespace: istio-system
data:
  fluent-bit.conf: |
    [SERVICE]
        Flush         1
        Log_Level     info
        Daemon        off
        Parsers_File  parsers.conf
        HTTP_Server   On
        HTTP_Listen   0.0.0.0
        HTTP_Port     2020

    [INPUT]
        Name              tail
        Path              /var/log/containers/*istio*proxy*.log
        Parser            docker
        Tag               istio.proxy
        Refresh_Interval  5
        Mem_Buf_Limit     50MB
        Skip_Long_Lines   On

    [INPUT]
        Name              tail
        Path              /var/log/containers/*istio*.log
        Parser            docker
        Tag               istio.component
        Refresh_Interval  5
        Mem_Buf_Limit     50MB
        Skip_Long_Lines   On

    [FILTER]
        Name                kubernetes
        Match               istio.*
        Kube_URL            https://kubernetes.default.svc:443
        Kube_CA_File        /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
        Kube_Token_File     /var/run/secrets/kubernetes.io/serviceaccount/token
        Merge_Log           On
        Keep_Log            Off
        K8S-Logging.Parser  On
        K8S-Logging.Exclude On
        Labels              On
        Annotations         On

    [OUTPUT]
        Name  forward
        Match istio.*
        Host  elasticsearch.logging.svc.cluster.local
        Port  24224

  parsers.conf: |
    [PARSER]
        Name        docker
        Format      json
        Time_Key    time
        Time_Format %Y-%m-%dT%H:%M:%S.%L
        Time_Keep   On
        Decode_Field_As escaped_utf8   log do_next
        Decode_Field_As json     log

    [PARSER]
        Name        istio_access_log
        Format      regex
        Regex       '^(?<start_time>[^ ]*) (?<method>[^ ]*) (?<path>[^ ]*) (?->[^ ]*) (?<protocol>[^ ]*) (?<code>[^ ]*) (?<response_flags>[^ ]*) (?<bytes_received>[^ ]*) (?<bytes_sent>[^ ]*) (?<duration>[^ ]*) (?<x_forwarded_for>[^ ]*) (?<user_agent>[^ ]*) (?<request_id>[^ ]*) (?<authority>[^ ]*) (?<upstream_service_time>[^ ]*) (?<upstream_address>[^ ]*) (?<upstream_response_flags>[^ ]*) (?<upstream_response_duration>[^ ]*) (?<x_forwarded_proto>[^ ]*) (?<upstream_cluster>[^ ]*) (?<upstream_local_address>[^ ]*) (?<downstream_local_address>[^ ]*) (?<downstream_remote_address>[^ ]*) (?<requested_server_name>[^ ]*) (?<route_name>[^ ]*)'

# Istio access logging configuration
apiVersion: v1
kind: ConfigMap
metadata:
  name: istio-proxy
  namespace: production
data:
  mesh: |-
    defaultConfig:
      # Enable access logging
      accessLogEncoding: JSON
      accessLogFile: /dev/stdout
      accessLogFormat: |
        {
          "timestamp": "%START_TIME%",
          "source": {
            "ip": "%DOWNSTREAM_REMOTE_ADDRESS%",
            "user_agent": "%REQ(USER-AGENT)%",
            "request_id": "%REQ(X-REQUEST-ID)%"
          },
          "destination": {
            "service": "%UPSTREAM_CLUSTER%",
            "host": "%UPSTREAM_HOST%",
            "ip": "%UPSTREAM_LOCAL_ADDRESS%"
          },
          "request": {
            "method": "%REQ(:METHOD)%",
            "path": "%REQ(X-ENVOY-ORIGINAL-PATH?:PATH)%",
            "protocol": "%PROTOCOL%",
            "headers": {
              "x-forwarded-for": "%REQ(X-FORWARDED-FOR)%",
              "user-agent": "%REQ(USER-AGENT)%",
              "x-request-id": "%REQ(X-REQUEST-ID)%",
              "x-b3-traceid": "%REQ(x-b3-traceid)%",
              "x-b3-spanid": "%REQ(x-b3-spanid)%",
              "x-b3-parentspanid": "%REQ(x-b3-parentspanid)%",
              "x-b3-sampled": "%REQ(x-b3-sampled)%",
              "x-ot-span-context": "%REQ(x-ot-span-context)%"
            }
          },
          "response": {
            "code": "%RESPONSE_CODE%",
            "flags": "%RESPONSE_FLAGS%",
            "code_details": "%RESPONSE_CODE_DETAILS%",
            "duration_ms": "%DURATION%",
            "bytes_sent": "%BYTES_SENT%",
            "bytes_received": "%BYTES_RECEIVED%"
          },
          "upstream": {
            "service_time": "%REQ(X-ENVOY-UPSTREAM-SERVICE-TIME)%",
            "address": "%UPSTREAM_HOST%",
            "response_flags": "%UPSTREAM_RESPONSE_FLAGS%",
            "response_duration": "%UPSTREAM_RESPONSE_DURATION%"
          }
        }
```

### Visualization

**📊 Kiali Visualization Setup**

```yaml
# Kiali installation
apiVersion: v1
kind: ConfigMap
metadata:
  name: kiali
  namespace: istio-system
data:
  config.yaml: |
    external_services:
      prometheus:
        url: "http://prometheus.monitoring.svc.cluster.local:9090"
      grafana:
        url: "http://grafana.monitoring.svc.cluster.local:3000"
      jaeger:
        url: "http://jaeger-query.istio-system.svc.cluster.local:16686"

    auth:
      strategy: "anonymous"

    server:
      port: 20001
      web_root: "/kiali"

    deployment:
      namespace: "istio-system"
      image_name: "quay.io/kiali/kiali"
      image_version: "v1.73"
      replicas: 1
      verbose_mode: true

    log_level: "info"

    istio_namespace: "istio-system"

    networking:
      istio_sidecar_injection: true

    external_services:
      custom_dashboards:
        enabled: true
        files:
          - "/etc/kiai/conf/custom-dashboards/*.json"

# Kiali deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: kiali
  namespace: istio-system
spec:
  replicas: 1
  selector:
    matchLabels:
      app: kiali
  template:
    metadata:
      labels:
        app: kiali
    spec:
      serviceAccountName: kiali
      containers:
      - name: kiali
        image: quay.io/kiali/kiali:v1.73
        command:
        - "/opt/kiali/kiali"
        - "-config"
        - "/etc/kiali/config.yaml"
        ports:
        - name: http-port
          containerPort: 20001
        env:
        - name: ACTIVE_NAMESPACE
          value: "istio-system"
        - name: LOG_LEVEL
          value: "info"
        - name: LOG_FORMAT
          value: "text"
        - name: SERVER_WEB_ROOT
          value: "/kiali"
        resources:
          requests:
            cpu: "100m"
            memory: "128Mi"
          limits:
            cpu: "500m"
            memory: "512Mi"
        volumeMounts:
        - name: kiali-configuration
          mountPath: "/etc/kiali/config.yaml"
          subPath: config.yaml
        - name: kiali-certs
          mountPath: "/etc/kiali/certs"
          readOnly: true
      volumes:
      - name: kiali-configuration
        configMap:
          name: kiali
      - name: kiali-certs
        secret:
          secretName: istio.istio-system.kiali-service-account
          optional: true

---
apiVersion: v1
kind: Service
metadata:
  name: kiali
  namespace: istio-system
  labels:
    app: kiali
spec:
  type: ClusterIP
  ports:
  - name: http
    port: 20001
    targetPort: 20001
  selector:
    app: kiali

# Service account and RBAC
apiVersion: v1
kind: ServiceAccount
metadata:
  name: kiali
  namespace: istio-system

---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: kiali
rules:
- apiGroups: [""]
  resources: ["configmaps", "endpoints", "namespaces", "nodes", "pods", "pods/log", "replicationcontrollers", "services"]
  verbs: ["get", "list", "watch"]
- apiGroups: ["extensions", "apps"]
  resources: ["deployments", "replicasets"]
  verbs: ["get", "list", "watch"]
- apiGroups: ["networking.istio.io"]
  resources: ["destinationrules", "gateways", "virtualservices", "workloadentries"]
  verbs: ["get", "list", "watch"]
- apiGroups: ["security.istio.io"]
  resources: ["authorizationpolicies", "peerauthentications", "requestauthentications"]
  verbs: ["get", "list", "watch"]

---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: kiali
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: kiali
subjects:
- kind: ServiceAccount
  name: kiali
  namespace: istio-system
```

***

## 🎯 **Advanced Features**

### Canary Deployments

**🐦 Canary Deployment Strategy**

```yaml
# Canary deployment with Istio
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-v2
  namespace: production
  labels:
    app: app
    version: v2
spec:
  replicas: 1
  selector:
    matchLabels:
      app: app
      version: v2
  template:
    metadata:
      labels:
        app: app
        version: v2
    spec:
      containers:
      - name: app
        image: my-app:v2.0.0
        ports:
        - containerPort: 8080
        readinessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 10
          periodSeconds: 5
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 30
          periodSeconds: 10

---
# Virtual service for canary deployment
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: app-canary
  namespace: production
spec:
  hosts:
  - app.production.svc.cluster.local
  http:
  - match:
    - headers:
        x-canary-user:
          exact: "true"
    route:
    - destination:
        host: app.production.svc.cluster.local
        subset: v2
      weight: 100
  - route:
    - destination:
        host: app.production.svc.cluster.local
        subset: v1
      weight: 90
    - destination:
        host: app.production.svc.cluster.local
        subset: v2
      weight: 10

# Progressive canary with gradual traffic shift
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
  name: app-rollout
  namespace: production
spec:
  replicas: 5
  strategy:
    canary:
      steps:
      - setWeight: 10
      - pause: {duration: 5m}
      - setWeight: 20
      - pause: {duration: 5m}
      - setWeight: 30
      - pause: {duration: 5m}
      - setWeight: 50
      - pause: {duration: 10m}
      - setWeight: 100
      canaryService: app-canary
      stableService: app
      trafficRouting:
        istio:
          virtualService:
            name: app-vsvc
            routes:
            - primary
          destinationRule:
            name: app-destrule
            canarySubsetName: canary
            stableSubsetName: stable
  selector:
    matchLabels:
      app: app
  template:
    metadata:
      labels:
        app: app
    spec:
      containers:
      - name: app
        image: my-app:v2.0.0
        ports:
        - containerPort: 8080
```

### A/B Testing

**🧪 A/B Testing Configuration**

```yaml
# A/B testing with Istio
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: app-ab-testing
  namespace: production
spec:
  hosts:
  - app.production.svc.cluster.local
  http:
  - match:
    - headers:
        x-ab-test:
          exact: "version-a"
    route:
    - destination:
        host: app.production.svc.cluster.local
        subset: version-a
      weight: 100
  - match:
    - headers:
        x-ab-test:
          exact: "version-b"
    route:
    - destination:
        host: app.production.svc.cluster.local
        subset: version-b
      weight: 100
  - match:
    - headers:
        x-user-type:
          exact: "premium"
    route:
    - destination:
        host: app.production.svc.cluster.local
        subset: version-b
      weight: 70
    - destination:
        host: app.production.svc.cluster.local
        subset: version-a
      weight: 30
  - match:
    - headers:
        x-user-type:
          exact: "basic"
    route:
    - destination:
        host: app.production.svc.cluster.local
        subset: version-a
      weight: 80
    - destination:
        host: app.production.svc.cluster.local
        subset: version-b
      weight: 20
  - route:
    - destination:
        host: app.production.svc.cluster.local
        subset: version-a
      weight: 50
    - destination:
        host: app.production.svc.cluster.local
        subset: version-b
      weight: 50

# Destination rule for A/B testing
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: app-ab-testing
  namespace: production
spec:
  host: app.production.svc.cluster.local
  subsets:
  - name: version-a
    labels:
      version: a
    trafficPolicy:
      loadBalancer:
        simple: ROUND_ROBIN
  - name: version-b
    labels:
      version: b
    trafficPolicy:
      loadBalancer:
        simple: LEAST_CONN
```

### Blue-Green Deployments

**🔵🟢 Blue-Green Deployment Strategy**

```yaml
# Blue-green deployment with Istio
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: app-blue-green
  namespace: production
spec:
  hosts:
  - app.production.svc.cluster.local
  http:
  - match:
    - headers:
        x-deployment:
          exact: "green"
    route:
    - destination:
        host: app.production.svc.cluster.local
        subset: green
      weight: 100
  - match:
    - headers:
        x-deployment:
          exact: "blue"
    route:
    - destination:
        host: app.production.svc.cluster.local
        subset: blue
      weight: 100
  - route:
    - destination:
        host: app.production.svc.cluster.local
        subset: blue
      weight: 100
    # Comment out the above line and uncomment below to switch to green
    # - destination:
    #     host: app.production.svc.cluster.local
    #     subset: green
    #   weight: 100

# Automated blue-green switch
apiVersion: batch/v1
kind: Job
metadata:
  name: blue-green-switch
  namespace: production
spec:
  template:
    spec:
      containers:
      - name: switch-script
        image: istio/istioctl:latest
        command:
        - /bin/sh
        - -c
        - |
          # Health check for green deployment
          for i in {1..10}; do
            if curl -f http://app-green.production.svc.cluster.local:8080/health; then
              echo "Green deployment is healthy"
              break
            fi
            echo "Waiting for green deployment to be healthy... attempt $i/10"
            sleep 10
          done

          # Switch traffic to green
          istioctl patch virtualservice app-blue-green -n production --patch '{"spec":{"http":[{"route":[{"destination":{"host":"app.production.svc.cluster.local","subset":"green"},"weight":100}]}]}}'
          echo "Traffic switched to green deployment"

          # Wait for user confirmation
          sleep 300

          # Rollback if needed
          # istioctl patch virtualservice app-blue-green -n production --patch '{"spec":{"http":[{"route":[{"destination":{"host":"app.production.svc.cluster.local","subset":"blue"},"weight":100}]}]}}'
      restartPolicy: Never
```

### Chaos Engineering

**💥 Chaos Engineering with Istio**

```yaml
# Chaos testing with fault injection
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: chaos-testing
  namespace: production
spec:
  hosts:
  - app.production.svc.cluster.local
  http:
  - match:
    - headers:
        x-chaos-test:
          exact: "latency"
    fault:
      delay:
        percentage:
          value: 100
        fixedDelay: 5s
    route:
    - destination:
        host: app.production.svc.cluster.local
  - match:
    - headers:
        x-chaos-test:
          exact: "error"
    fault:
      abort:
        percentage:
          value: 50
        httpStatus: 503
    route:
    - destination:
        host: app.production.svc.cluster.local
  - match:
    - headers:
        x-chaos-test:
          exact: "timeout"
    timeout: 1s
    fault:
      delay:
        percentage:
          value: 100
        fixedDelay: 2s
    route:
    - destination:
        host: app.production.svc.cluster.local

# Chaos monkey experiment
apiVersion: batch/v1
kind: CronJob
metadata:
  name: chaos-monkey
  namespace: production
spec:
  schedule: "0 14 * * 1-5"  # Weekdays at 2 PM
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: chaos-monkey
            image: istio/istioctl:latest
            command:
            - /bin/sh
            - -c
            - |
              # Select random pod to terminate
              POD=$(kubectl get pods -n production -l app=app -o jsonpath='{.items[0].metadata.name}')
              echo "Terminating pod: $POD"

              # Inject faults before termination
              istioctl patch virtualservice app-chaos -n production --patch '{"spec":{"http":[{"fault":{"delay":{"percentage":{"value":50},"fixedDelay":"2s"}}}]} }'
              sleep 30

              # Terminate pod
              kubectl delete pod $POD -n production

              # Remove faults after termination
              istioctl patch virtualservice app-chaos -n production --patch '{"spec":{"http":[{"route":[{"destination":{"host":"app.production.svc.cluster.local"}}]}]}}'
          restartPolicy: OnFailure
```

### Multi-Cluster Mesh

**🌐 Multi-Cluster Service Mesh**

```yaml
# Multi-cluster mesh configuration
apiVersion: v1
kind: ConfigMap
metadata:
  name: istio
  namespace: istio-system
data:
  mesh: |-
    # Multi-cluster mesh configuration
    meshConfig:
      accessLogFile: /dev/stdout
      defaultConfig:
        # Enable multi-cluster
        discoveryAddress: istiod.istio-system.svc:15012
        proxyMetadata:
          # Enable cross-cluster traffic
          ISTIO_META_DNS_CAPTURE: "true"
          ISTIO_META_DNS_AUTO_ALLOCATE: "true"
        # Enable service entry for cross-cluster
        trustDomain: "cluster.local"
        # Enable multi-cluster networking
        networking:
          trafficPolicy:
            connectionPool:
              tcp:
                maxConnections: 100
              http:
                http1MaxPendingRequests: 50
            outlierDetection:
              consecutiveErrors: 3
              interval: 30s
              baseEjectionTime: 30s

# Cross-cluster service entry
apiVersion: networking.istio.io/v1beta1
kind: ServiceEntry
metadata:
  name: remote-cluster-services
  namespace: production
spec:
  hosts:
  - "*.remote-cluster.svc.cluster.local"
  location: MESH_INTERNAL
  resolution: DNS
  addresses:
  - 240.0.0.0/16
  ports:
  - number: 80
    name: http
    protocol: HTTP
  - number: 443
    name: https
    protocol: HTTPS

# Multi-cluster gateway configuration
apiVersion: networking.istio.io/v1beta1
kind: Gateway
metadata:
  name: cross-cluster-gateway
  namespace: istio-system
spec:
  selector:
    istio: eastwestgateway
  servers:
  - port:
      number: 15443
      name: tls
      protocol: TLS
    tls:
      mode: AUTO_PASSTHROUGH
      credentialName: eastwestgateway-certs
    hosts:
    - "*.remote-cluster.svc.cluster.local"
    - "*.local-cluster.svc.cluster.local"

# Multi-cluster traffic policy
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: cross-cluster-traffic-policy
  namespace: production
spec:
  host: app.production.svc.cluster.local
  trafficPolicy:
    loadBalancer:
      localityLbSetting:
        enabled: true
        failover:
        - from: us-west-2
          to: us-east-1
        - from: us-east-1
          to: us-west-2
    connectionPool:
      tcp:
        maxConnections: 100
      http:
        http1MaxPendingRequests: 50
        maxRequestsPerConnection: 10
    circuitBreaker:
      consecutiveErrors: 3
      interval: 30s
      baseEjectionTime: 30s
      maxEjectionPercent: 50
      minHealthPercent: 50
```

***

## 🎯 **Best Practices**

### **🔧 Service Mesh Implementation**

1. **Gradual Adoption**
   * Start with non-critical services
   * Enable per-namespace injection
   * Monitor performance impact
   * Expand to production workloads
2. **Security First**
   * Enable mTLS from the beginning
   * Implement proper authentication
   * Set up authorization policies
   * Regular security audits
3. **Observability**
   * Configure comprehensive monitoring
   * Set up distributed tracing
   * Implement centralized logging
   * Create meaningful dashboards

### **📊 Performance Optimization**

1. **Resource Management**
   * Monitor sidecar resource usage
   * Optimize connection pools
   * Configure appropriate timeouts
   * Tune circuit breaking settings
2. **Network Optimization**
   * Use locality-aware load balancing
   * Implement proper traffic splitting
   * Configure connection draining
   * Optimize for latency

### **🛡️ Security Best Practices**

1. **mTLS Implementation**
   * Start with permissive mode
   * Gradually move to strict mode
   * Monitor certificate rotation
   * Test connectivity thoroughly
2. **Policy Enforcement**
   * Implement least privilege access
   * Regular policy reviews
   * Automated compliance checking
   * Incident response procedures

***

## 🔗 **Referensi**

### **📚 Dokumentasi Resmi**

* [Istio Documentation](https://istio.io/docs/)
* [Istio Installation Guide](https://istio.io/docs/setup/install/)
* [Istio Configuration Reference](https://istio.io/docs/reference/config/)
* [Istio Architecture](https://istio.io/latest/docs/ops/architecture/)

### **🛠️ Istio Tools**

* [Istioctl CLI](https://istio.io/docs/reference/commands/istioctl/)
* [Kiali Visualization](https://kiali.io/)
* [Jaeger Tracing](https://www.jaegertracing.io/)
* [Prometheus Metrics](https://prometheus.io/)

### **📖 Learning Resources**

* [Istio Service Mesh Patterns](https://istio.io/latest/docs/concepts/traffic-management/)
* [Istio Security Best Practices](https://istio.io/latest/docs/concepts/security/)
* [Multi-Cluster Mesh Guide](https://istio.io/latest/docs/tasks/multicluster/)

***

\*🔗 \**Service mesh provides powerful capabilities but requires careful planning and implementation*
