# Catatan Seekor: DevOps

## Overview

DevOps adalah kombinasi dari filosofi budaya, praktik, dan tools yang meningkatkan kemampuan organisasi untuk memberikan aplikasi dan layanan dengan kecepatan tinggi. DevOps memungkinkan tim development dan operations untuk bekerja sama secara efisien melalui otomatisasi, continuous integration/continuous deployment (CI/CD), dan monitoring yang komprehensif.

## Prinsip DevOps

### 1. Culture & Collaboration

* **Shared Responsibility** - Development dan Operations bertanggung jawab bersama
* **Cross-functional Teams** - Tim yang terdiri dari berbagai skill set
* **Continuous Learning** - Belajar dari kegagalan dan sukses
* **Transparency** - Visibilitas penuh terhadap proses dan metrics

### 2. Automation

* **Infrastructure as Code (IaC)** - Mendefinisikan infrastruktur dalam kode
* **Automated Testing** - Testing otomatis di setiap stage
* **Automated Deployment** - Deployment tanpa intervensi manual
* **Automated Monitoring** - Alerting dan response otomatis

### 3. Measurement & Monitoring

* **Metrics Collection** - Mengumpulkan data performa dan availability
* **Real-time Monitoring** - Monitoring real-time untuk proactive response
* **Feedback Loops** - Feedback cepat untuk continuous improvement
* **Business Metrics** - Mengukur impact terhadap business goals

## Core Practices

### Continuous Integration (CI)

```yaml
# Example GitLab CI/CD Pipeline
stages:
  - build
  - test
  - deploy

build:
  stage: build
  script:
    - docker build -t myapp:$CI_COMMIT_SHA .
    - docker push registry.example.com/myapp:$CI_COMMIT_SHA
  only:
    - main

test:
  stage: test
  script:
    - npm install
    - npm run test:unit
    - npm run test:integration
  coverage: '/Coverage: \d+\.\d+%/'

deploy:
  stage: deploy
  script:
    - kubectl set image deployment/myapp myapp=registry.example.com/myapp:$CI_COMMIT_SHA
  environment:
    name: production
  only:
    - main
```

### Continuous Deployment (CD)

```yaml
# Example GitHub Actions Workflow
name: Deploy to Production

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    
    - name: Build Docker image
      run: |
        docker build -t myapp:${{ github.sha }} .
        docker tag myapp:${{ github.sha }} myapp:latest
    
    - name: Deploy to Kubernetes
      run: |
        kubectl config set-cluster k8s --server=${{ secrets.KUBE_URL }}
        kubectl config set-credentials admin --token=${{ secrets.KUBE_TOKEN }}
        kubectl set image deployment/myapp myapp=myapp:${{ github.sha }}
```

### Infrastructure as Code (IaC)

```hcl
# Example Terraform Configuration
provider "aws" {
  region = "us-west-2"
}

resource "aws_instance" "web" {
  ami           = "ami-12345678"
  instance_type = "t3.micro"
  
  tags = {
    Name = "WebServer"
    Environment = "Production"
  }
}

resource "aws_security_group" "web" {
  name        = "web-sg"
  description = "Security group for web servers"
  
  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  
  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
```

## Containerization

### Docker Best Practices

```dockerfile
# Multi-stage build example
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

FROM node:18-alpine AS runtime
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
```

### Docker Compose

```yaml
version: '3.8'
services:
  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
      - DATABASE_URL=postgresql://user:pass@db:5432/mydb
    depends_on:
      - db
    volumes:
      - app-data:/app/data
  
  db:
    image: postgres:15
    environment:
      - POSTGRES_DB=mydb
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=pass
    volumes:
      - db-data:/var/lib/postgresql/data

volumes:
  app-data:
  db-data:
```

## Orchestration

### Kubernetes Basics

```yaml
# Example Kubernetes Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
  labels:
    app: myapp
spec:
  replicas: 3
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
      - name: myapp
        image: myapp:latest
        ports:
        - containerPort: 3000
        resources:
          requests:
            memory: "64Mi"
            cpu: "250m"
          limits:
            memory: "128Mi"
            cpu: "500m"
        livenessProbe:
          httpGet:
            path: /health
            port: 3000
          initialDelaySeconds: 30
          periodSeconds: 10
```

### Kubernetes Services

```yaml
apiVersion: v1
kind: Service
metadata:
  name: myapp-service
spec:
  selector:
    app: myapp
  ports:
    - protocol: TCP
      port: 80
      targetPort: 3000
  type: LoadBalancer
```

## Monitoring & Observability

### Prometheus Configuration

```yaml
# prometheus.yml
global:
  scrape_interval: 15s

scrape_configs:
  - job_name: 'kubernetes-pods'
    kubernetes_sd_configs:
      - role: pod
    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__
```

### Grafana Dashboard

```json
{
  "dashboard": {
    "title": "Application Metrics",
    "panels": [
      {
        "title": "Request Rate",
        "type": "graph",
        "targets": [
          {
            "expr": "rate(http_requests_total[5m])",
            "legendFormat": "{{method}} {{route}}"
          }
        ]
      },
      {
        "title": "Response Time",
        "type": "graph",
        "targets": [
          {
            "expr": "histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))",
            "legendFormat": "95th percentile"
          }
        ]
      }
    ]
  }
}
```

## Security

### Container Security

```yaml
# Security context in Kubernetes
securityContext:
  runAsNonRoot: true
  runAsUser: 1000
  capabilities:
    drop:
      - ALL
  readOnlyRootFilesystem: true
  allowPrivilegeEscalation: false
```

### Network Policies

```yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-app-traffic
spec:
  podSelector:
    matchLabels:
      app: myapp
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    ports:
    - protocol: TCP
      port: 3000
```

## CI/CD Tools

### Jenkins Pipeline

```groovy
pipeline {
    agent any
    
    stages {
        stage('Build') {
            steps {
                echo 'Building..'
                sh 'docker build -t myapp .'
            }
        }
        stage('Test') {
            steps {
                echo 'Testing..'
                sh 'npm test'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying....'
                sh 'kubectl apply -f k8s/'
            }
        }
    }
    
    post {
        always {
            echo 'Pipeline completed'
        }
        success {
            echo 'Pipeline succeeded!'
        }
        failure {
            echo 'Pipeline failed!'
        }
    }
}
```

### GitLab CI/CD

```yaml
stages:
  - build
  - test
  - security
  - deploy

variables:
  DOCKER_DRIVER: overlay2
  DOCKER_TLS_CERTDIR: "/certs"

build:
  stage: build
  image: docker:latest
  services:
    - docker:dind
  script:
    - docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA .
    - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
  only:
    - main

test:
  stage: test
  image: node:18
  script:
    - npm install
    - npm run test:unit
    - npm run test:integration
  coverage: '/Coverage: \d+\.\d+%/'

security:
  stage: security
  image: aquasec/trivy:latest
  script:
    - trivy image $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA --exit-code 1 --severity HIGH,CRITICAL

deploy:
  stage: deploy
  image: bitnami/kubectl:latest
  script:
    - kubectl config set-cluster k8s --server=$KUBE_URL
    - kubectl config set-credentials admin --token=$KUBE_TOKEN
    - kubectl set image deployment/myapp myapp=$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
  environment:
    name: production
  only:
    - main
```

## Cloud Platforms

### AWS DevOps

```yaml
# AWS CodePipeline
version: 0.2
phases:
  install:
    runtime-versions:
      nodejs: 18
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com
  build:
    commands:
      - echo Build started on `date`
      - docker build -t myapp .
      - docker tag myapp:latest $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/myapp:$IMAGE_TAG
  post_build:
    commands:
      - echo Build completed on `date`
      - echo Pushing the Docker image...
      - docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/myapp:$IMAGE_TAG
```

### Google Cloud Platform

```yaml
# Cloud Build configuration
steps:
  - name: 'gcr.io/cloud-builders/docker'
    args: ['build', '-t', 'gcr.io/$PROJECT_ID/myapp:$COMMIT_SHA', '.']
  - name: 'gcr.io/cloud-builders/docker'
    args: ['push', 'gcr.io/$PROJECT_ID/myapp:$COMMIT_SHA']
  - name: 'gcr.io/cloud-builders/kubectl'
    args:
      - 'set'
      - 'image'
      - 'deployment/myapp'
      - 'myapp=gcr.io/$PROJECT_ID/myapp:$COMMIT_SHA'
    env:
      - 'CLOUDSDK_COMPUTE_REGION=us-central1'
      - 'CLOUDSDK_CONTAINER_CLUSTER=my-cluster'
```

## Best Practices

### 1. Security

* **Scan containers** untuk vulnerabilities
* **Use least privilege** principle
* **Implement network policies** di Kubernetes
* **Regular security updates** untuk dependencies
* **Secret management** yang proper

### 2. Performance

* **Resource limits** dan requests di Kubernetes
* **Horizontal Pod Autoscaling** (HPA)
* **Load balancing** yang efektif
* **Caching strategies** untuk aplikasi
* **Database optimization**

### 3. Reliability

* **Health checks** dan readiness probes
* **Circuit breakers** untuk external services
* **Retry mechanisms** dengan exponential backoff
* **Graceful degradation** strategies
* **Disaster recovery** plans

### 4. Monitoring

* **Centralized logging** dengan ELK stack
* **Metrics collection** dengan Prometheus
* **Alerting** untuk critical issues
* **Tracing** dengan Jaeger atau Zipkin
* **Business metrics** tracking

## Referensi

### Tutorial dan Artikel

* [8 Tips for Containerizing Django Apps](https://hackernoon.com/8-tips-for-containerizing-django-apps-5340647632a4)
* [A Complete List of HTTP Status Lines](https://www.lifewire.com/http-status-lines-2623465)
* [Application Logs from Kubernetes to S3 and Elasticsearch using Fluentd](https://medium.com/@alluri.prithvi/application-logs-from-kubernetes-to-s3-and-elasticsearch-using-fluentd-2f1b09a9872e)
* [Best Practices for Logging in Docker Swarm](https://www.loggly.com/blog/best-practices-for-logging-in-docker-swarm/)
* [Blue-green Deployments, A/B Testing, and Canary Releases](https://blog.christianposta.com/deploy/blue-green-deployments-a-b-testing-and-canary-releases/)
* [Cara Install Dan Setup Rancher 2.x (Latest), Kubernetes/Docker Di Linux](https://www.ayies.com/cara-install-dan-setup-rancher-2-x-latest-kubernetes-docker-di-linux/)
* [CentOS 7 VirtualBox no internet access](https://superuser.com/questions/915536/centos-7-virtualbox-no-internet-access)
* [Configure logging drivers](https://docs.docker.com/config/containers/logging/configure/)
* [Copying SSH Key From Root To Another User On Same Machine](https://askubuntu.com/questions/1218023/copying-ssh-key-from-root-to-another-user-on-same-machine)
* [Create Jenkins Pipeline for automating Docker image creation and push docker image into Docker Hub | Dockerize Python App](https://www.coachdevops.com/2020/05/automate-docker-builds-using-jenkins.html)
* [Do I Need an API Gateway if I Use a Service Mesh?](https://blog.christianposta.com/microservices/do-i-need-an-api-gateway-if-i-have-a-service-mesh/)
* [Docker Reference Architecture: Docker Logging Design and Best Practices](https://success.docker.com/article/logging-best-practices)
* [Docker orchestration with Rancher](https://medium.com/@griggheo/docker-orchestration-with-rancher-1e573cc45707)
* [Docker-Based Build Pipelines (Part 2) - Continuous Deployment](https://rancher.com/continuous-deployment)
* [Docker-based build pipelines (Part 1) - Continuous Integration and Testing](https://rancher.com/docker-based-build-pipelines-part-1-continuous-integration-and-testing/)
* [Gitlab CI to Slack integration](https://faun.pub/gitlab-to-slack-integration-c58555116973)
* [HOW TO CREATE USERS AND GROUPS IN CENTOS7?](https://manage.accuwebhosting.com/knowledgebase/2959/How-to-create-users-and-groups-in-CentOS7.html)
* [How To Import and Export Databases in MySQL or MariaDB](https://www.digitalocean.com/community/tutorials/how-to-import-and-export-databases-in-mysql-or-mariadb)
* [How To Install / Enable OpenSSH On CentOS 7](https://phoenixnap.com/kb/how-to-enable-ssh-centos-7)
* [How To Remove Docker Containers, Images, Volumes, and Networks](https://linuxize.com/post/how-to-remove-docker-images-containers-volumes-and-networks/)
* [How To Secure Nginx with Let's Encrypt on Ubuntu 20.04](https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-20-04)
* [How To Set Up SSH Keys on CentOS 7](https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys-on-centos7)
* [How To Set Up a Continuous Deployment Pipeline with GitLab CI/CD on Ubuntu 18.04](https://www.digitalocean.com/community/tutorials/how-to-set-up-a-continuous-deployment-pipeline-with-gitlab-ci-cd-on-ubuntu-18-04)
* [How To Set Up an Elasticsearch, Fluentd and Kibana (EFK) Logging Stack on Kubernetes](https://www.digitalocean.com/community/tutorials/how-to-set-up-an-elasticsearch-fluentd-and-kibana-efk-logging-stack-on-kubernetes)
* [How do I find my SSH public key on Windows server?](https://stackoverflow.com/questions/44135974/how-do-i-find-my-ssh-public-key-on-windows-server)
* [How to Fix "firewall-cmd: command not found" Error in RHEL/CentOS 7](https://www.tecmint.com/fix-firewall-cmd-command-not-found-error/)
* [How to Install Rancher Docker Container Manager on CentOS 7](https://www.howtoforge.com/tutorial/centos-rancher-docker-container-management-platform/)
* [How to Install and Use PHP Composer on CentOS 7](https://linuxize.com/post/how-to-install-and-use-composer-on-centos-7/)
* [How to install Apache, PHP 7.3 and MySQL on CentOS 7.6](https://www.howtoforge.com/tutorial/centos-lamp-server-apache-mysql-php/)
* [How to setup Rancher 2 in an airgap / offline environment](https://medium.com/@superseb/how-to-setup-rancher-2-in-an-air-gapped-environment-fd35a0aae792)
* [How to switch user in Centos](https://stackoverflow.com/questions/21882645/how-to-switch-user-in-centos)
* [How to use Go with a private GitLab repo](https://stackoverflow.com/questions/29707689/how-to-use-go-with-a-private-gitlab-repo)
* [Initial Server Setup with CentOS 7](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-centos-7)
* [Install Production Kubernetes Cluster with Rancher RKE](https://computingforgeeks.com/install-kubernetes-production-cluster-using-rancher-rke/)
* [Interface IP address is removed automatically on CentOs running inside VirtualBox](https://serverfault.com/questions/514340/interface-ip-address-is-removed-automatically-on-centos-running-inside-virtualbo)
* [Jira DVCS connector](https://docs.gitlab.com/ee/integration/jira/dvcs.html)
* [Make RESTful API calls in Rancher/Docker without a port](https://stackoverflow.com/questions/49758202/make-restful-api-calls-in-rancher-docker-without-a-port)
* [Manage All of Your Clusters as One](https://rancher.com/products/rancher/multi-cluster-management/)
* [Membuat VPS di Google Cloud Platform](https://medium.com/@yunusmuhammad007/membuat-vps-di-google-cloud-platform-2be081c91d74)
* [NETCOMM Acronyms](http://geocities.ws/eadorio/netcomm-acronyms.html)
* [Process issues with smart commits](https://support.atlassian.com/jira-software-cloud/docs/process-issues-with-smart-commits/)
* [Quick DevOps](https://www.quickdevops.com)
* [Reset (clean up) a Rancher Docker Host](https://www.claudiokuenzler.com/blog/674/reset-clean-up-a-rancher-docker-host)
* [Run Docker Registry on CentOS 7 With Let's Encrypt SSL](https://computingforgeeks.com/install-and-configure-docker-registry-on-centos-7/)
* [Top 10 Docker Logging Gotchas](https://dzone.com/articles/top-10-docker-logging-gotchas)
* [Ultimate list of Cheat Sheet for System Administrator](https://geekflare.com/cheat-sheet-system-admin/)
* [Update: Rancher 2.5 alone install k3s and can't start without privileged](https://github.com/rancher/rancher/issues/29513)
* [Use SSH Public Key Authentication on Linux, macOS, and Windows](https://www.linode.com/docs/guides/use-public-key-authentication-with-ssh/)
* [Where is kong.conf file?](https://stackoverflow.com/questions/56007431/where-is-kong-conf-file)
* [cURL SSL connect error 35 with NSS error -5961](https://stackoverflow.com/questions/21887315/curl-ssl-connect-error-35-with-nss-error-5961)
* [go private modules in gitlab](https://seankhliao.com/blog/12021-04-29-go-private-modules-in-gitlab/)
* [rancher Certificate Management](https://rancher.com/docs/rke/latest/en/cert-mgmt/)
* [rancher \[2.2.4\] etcd/controlplane master not registering on new clusters](https://github.com/rancher/rancher/issues/21514#issuecomment-562834860)

## Course

* [Qwiklabs](https://www.qwiklabs.com) - Hands-on labs untuk cloud platforms
* [DevOps Bootcamp](https://www.udemy.com/course/complete-devops-bootcamp/) - Complete DevOps course
* [Kubernetes for Developers](https://www.coursera.org/specializations/kubernetes-for-developers) - Kubernetes specialization
* [AWS DevOps Engineer](https://aws.amazon.com/certification/certified-devops-engineer-professional/) - AWS certification

## Tools

* [Chmod command](https://chmodcommand.com) - File permissions calculator
* [CloudCraft](https://www.cloudcraft.co) - AWS architecture diagrams
* [Terraform](https://www.terraform.io/) - Infrastructure as Code
* [Ansible](https://www.ansible.com/) - Configuration management
* [Jenkins](https://jenkins.io/) - CI/CD automation
* [GitLab CI/CD](https://docs.gitlab.com/ee/ci/) - GitLab pipelines
* [GitHub Actions](https://github.com/features/actions) - GitHub automation
* [Prometheus](https://prometheus.io/) - Monitoring and alerting
* [Grafana](https://grafana.com/) - Visualization and analytics
* [ELK Stack](https://www.elastic.co/what-is/elk-stack) - Logging solution

## Testing

* [JMeter](https://jmeter.apache.org/usermanual/get-started.html) - Load testing
* [Vegeta](https://pkg.go.dev/github.com/tsenart/vegeta/) - HTTP load testing
* [Selenium](https://www.selenium.dev/) - Browser automation
* [Postman](https://www.postman.com/) - API testing
* [SonarQube](https://www.sonarqube.org/) - Code quality analysis

## Other

* [Awesome Tech](https://awesome-tech.readthedocs.io) - Curated tech resources
* [DevOps Roadmap](https://roadmap.sh/devops) - DevOps learning path
* [CNCF Landscape](https://landscape.cncf.io/) - Cloud native tools
* [DevOps Weekly](https://www.devopsweekly.com/) - Weekly DevOps newsletter

## Tips dan Trik

### 1. Getting Started

* Mulai dengan **CI/CD pipeline** sederhana
* Implementasikan **Infrastructure as Code** secara bertahap
* Gunakan **containerization** untuk consistency
* Setup **monitoring** sejak awal

### 2. Best Practices

* **Automate everything** yang bisa diotomatisasi
* **Test in production-like** environments
* **Monitor everything** yang penting
* **Document processes** dan procedures
* **Security first** approach

### 3. Common Pitfalls

* Jangan **over-engineer** solusi
* Hindari **manual processes** yang bisa diotomatisasi
* Jangan lupa **backup dan disaster recovery**
* Monitor **costs** di cloud platforms
* Implementasikan **security** sejak awal

DevOps adalah journey yang berkelanjutan untuk meningkatkan efisiensi, reliability, dan kecepatan delivery. Dengan tools dan practices yang tepat, tim dapat mencapai goals DevOps dan memberikan value yang lebih baik kepada customers.
