L
Infrastructure as Code (IaC) β€’ Literally Web ID

Automasi Infrastruktur Multi-Cloud Skala Enterprise Menggunakan Terraform dan Ansible

⏱️ 15 menit baca β€’ πŸ“… 19 Oct 2026 β€’ πŸ‘οΈ 4 views
Automasi Infrastruktur Multi-Cloud Skala Enterprise Menggunakan Terraform dan Ansible

1. Konteks Industri & Analisis Akar Masalah

Dalam lanskap teknologi enterprise modern, pengelolaan infrastruktur berbasis manual (point-and-click melalui konsol cloud AWS, GCP, atau Azure) telah menjadi technical debt yang sangat mematikan. Ketika sebuah perusahaan berkembang dari rintisan menjadi korporasi skala enterprise, kompleksitas arsitektur web melonjak secara eksponensial. Sistem yang awalnya hanya terdiri dari sebuah virtual machine tunggal kini berubah menjadi ekosistem terdistribusi yang melibatkan Multi-Cloud VPC, Application Load Balancer, auto-scaling compute instances, managed database clusters (MySQL/MariaDB), caching layers (Redis), sistem antrean (RabbitMQ/Supervisor), edge caching (Cloudflare CDN), hingga WAF dan aturan keamanan ketat.

Bottleneck Performa dan Keamanan Dunia Nyata

Tanpa automasi infrastruktur yang presisi, tim infrastruktur dan DevOps sering kali terjebak dalam masalah klasik:

  • Konfigurasi Drift (Configuration Drift): Perbedaan konfigurasi antara environment Staging dan Production yang menyebabkan bug misterius hanya muncul saat live.
  • Human Error: Kesalahan manual dalam mengatur Security Group, membuka port sensitif (seperti port 22, 3306, atau 6379 secara publik), atau kesalahan konfigurasi DNS (SPF, DKIM, DMARC) yang berakibat pada reputasi domain email.
  • Waktu Pemulihan yang Lambat (High MTTR): Saat terjadi kegagalan infrastruktur total (Disaster Recovery), pemulihan manual memakan waktu berjam-jam bahkan berhari-hari, mengakibatkan kerugian finansial yang masif.

Kondisi Sebelum vs Sesudah Penerapan

  • Sebelum: Proses provisioning server memakan waktu 3 hari dengan 50+ langkah manual. Konfigurasi web server (Nginx/Apache), PHP-FPM, dan database dilakukan secara langsung lewat SSH, menyebabkan inkonsistensi yang tidak terlacak oleh version control.
  • Sesudah: Infrastruktur didefinisikan sebagai kode (Infrastructure as Code) menggunakan Terraform, dan konfigurasi sistem diotomatisasi secara penuh menggunakan Ansible Playbooks. Proses provisioning seluruh stack web enterprise dari nol hingga siap melayani traffic tinggi dapat diselesaikan dalam waktu kurang dari 8 menit dengan jaminan 100% konsistensi.

2. Konsep Inti & Deep Dive Arsitektur

Automasi infrastruktur enterprise mengombinasikan dua pilar utama: Terraform untuk Infrastructure Provisioning (Layer 3/4 network, compute, storage, DNS) dan Ansible untuk Configuration Management & Application Deployment (OS hardening, web server stack, runtime, background workers).

Alur Eksekusi End-to-End

  1. Terraform Apply: Membaca berkas HCL, melakukan plan terhadap state, berinteraksi dengan API provider (AWS/GCP), membuat VPC, Subnet, Internet Gateway, Security Groups, dan melahirkan Instance Compute.
  2. Dynamic Inventory: Ansible secara otomatis mendeteksi IP instance yang baru dibuat melalui plugin inventory cloud atau keluaran output Terraform.
  3. Ansible Playbook Execution: Melakukan SSH ke target, memasang dependensi (Nginx, PHP-FPM, Redis, Supervisor), mengatur SSL/TLS via Let's Encrypt, mengonfigurasi Postfix mail relay, dan menyalin virtual host web.
+-------------------------------------------------------------------+
|                        Developer Workstation                      |
+-------------------------------------------------------------------+
          |                                       |
          v                                       v
+--------------------+                  +--------------------+
|  Terraform Engine  |                  |   Ansible Engine   |
+--------------------+                  +--------------------+
  | (Provisioning)                        | (Configuration)
  v                                       v
+-------------------------------------------------------------------+
|                        Multi-Cloud Provider                       |
|  [ VPC / Subnet ] -> [ Compute Instances ] -> [ Cloudflare DNS ]  |
+-------------------------------------------------------------------+
                                          |
                                          v
+-------------------------------------------------------------------+
|                     Managed Enterprise Stack                      |
|  [ Nginx + PHP-FPM ] [ MySQL / Redis ] [ Postfix SMTP ] [ S3 Sync ] |
+-------------------------------------------------------------------+

3. Perbandingan Komparatif / Analisis Pendekatan

Untuk memahami mengapa kombinasi Terraform dan Ansible menjadi standar industri enterprise, mari kita bandingkan dengan pendekatan alternatif.

Parameter Komparasi Terraform + Ansible (Rekomendasi) AWS CloudFormation + Bash Scripts Pure Kubernetes (K8s) Operator pulumi + Chef
Cakupan Multi-Cloud & OS Configuration Vendor-Lockin (AWS Only) Containerized workloads Multi-Cloud (Code-based)
Kurva Belajar Menengah (HCL & YAML) Menengah (JSON/YAML) Curam (Kubernetes Ecosystem) Curam (Python/TS/Go)
State Management Remote Backend (S3/Consul) Native Cloud Storage Etcd (Cluster State) Pulumi Service / S3
Manajemen OS Sangat Baik (via Ansible) Buruk (Perlu User Data / AMI) Terbatas (Container-centric) Baik (via Chef Recipes)
Kompleksitas Ops Rendah-Menengah Rendah Sangat Tinggi Menengah-Tinggi

[!IMPORTANT] Jangan pernah menggunakan Terraform untuk manajemen file konfigurasi aplikasi di dalam OS secara berlebihan (misal: menggunakan file provisioner secara masif). Gunakan Terraform murni untuk infrastruktur dasar (immutable infrastructure), dan serahkan manajemen konfigurasi aplikasi sepenuhnya kepada Ansible.


4. Prasyarat Sistem & Persiapan Lingkungan

Sebelum memulai implementasi, pastikan environment lokal atau CI/CD runner Anda memiliki toolchain berikut terinstal dengan versi minimal:

  • Terraform: >= 1.6.0
  • Ansible: >= 2.15.0
  • Python: >= 3.10 (beserta boto3 jika menggunakan AWS)
  • Git & SSH Client

Verifikasi instalasi dengan perintah terminal:

terraform version
ansible --version
python3 -c "import boto3; print(boto3.__version__)"

Struktur direktori proyek yang akan kita bangun:

enterprise-infra/
β”œβ”€β”€ terraform/
β”‚   β”œβ”€β”€ main.tf
β”‚   β”œβ”€β”€ variables.tf
β”‚   β”œβ”€β”€ outputs.tf
β”‚   └── backend.tf
└── ansible/
    β”œβ”€β”€ inventory.ini
    β”œβ”€β”€ playbook.yml
    └── roles/
        └── web_stack/
            β”œβ”€β”€ tasks/
            β”‚   └── main.yml
            └── templates/
                └── nginx.conf.j2

5. Panduan Implementasi Langkah demi Langkah

Langkah 1: Konfigurasi Terraform Backend & Provider (terraform/backend.tf)

terraform {
  required_version = ">= 1.6.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "~> 4.0"
    }
  }
  backend "s3" {
    bucket         = "enterprise-terraform-state-bucket-prod"
    key            = "web-infrastructure/terraform.tfstate"
    region         = "ap-southeast-1"
    dynamodb_table = "terraform-lock-table"
    encrypt        = true
  }
}

provider "aws" {
  region = "ap-southeast-1"
}

provider "cloudflare" {
  api_token = var.cloudflare_api_token}

Langkah 2: Definisi Infrastruktur Utama (terraform/main.tf)

resource "aws_vpc" "main" {
  cidr_block           = "10.100.0.0/16"
  enable_dns_hostnames = true
  enable_dns_support   = true

  tags = {
    Name        = "enterprise-vpc"
    Environment = "production"
  }
}

resource "aws_subnet" "public" {
  vpc_id                  = aws_vpc.main.id
  cidr_block              = "10.100.1.0/24"
  map_public_ip_on_launch = true
  availability_zone       = "ap-southeast-1a"

  tags = {
    Name = "enterprise-public-subnet"
  }
}

resource "aws_security_group" "web" {
  name        = "enterprise-web-sg"
  description = "Allow HTTP, HTTPS, and SSH"
  vpc_id      = aws_vpc.main.id

  ingress {
    description = "TLS from Anywhere"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    description = "HTTP from Anywhere"
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    description = "SSH from Bastion/Office"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["203.0.113.50/32"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_instance" "web_server" {
  ami                    = "ami-0c55b159cbfafe1f0" # Ubuntu 22.04 LTS
  instance_type          = "t3.medium"
  subnet_id              = aws_subnet.public.id
  vpc_security_group_ids = [aws_security_group.web.id]
  key_name               = "enterprise-deploy-key"

  root_block_device {
    volume_size           = 50
    volume_type           = "gp3"
    encrypted             = true
    delete_on_termination = false
  }

  tags = {
    Name = "enterprise-web-node-01"
  }
}

resource "cloudflare_record" "web" {
  zone_id = var.cloudflare_zone_id
  name    = "app"
  value   = aws_instance.web_server.public_ip
  type    = "A"
  ttl     = 1
  proxied = true
}

Langkah 3: Ansible Inventory (ansible/inventory.ini)

[webservers]
app-node-01 ansible_host=54.255.x.x ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/enterprise-deploy-key.pem

[webservers:vars]
ansible_python_interpreter=/usr/bin/python3

Langkah 4: Ansible Playbook Utama (ansible/playbook.yml)

---
- name: Provision Enterprise Web Stack
  hosts: webservers
  become: yes
  vars:
    app_domain: "app.example.com"
  roles:
    - web_stack

Langkah 5: Ansible Role Tasks (ansible/roles/web_stack/tasks/main.yml)

---
- name: Update apt cache and upgrade system packages
  apt:
    update_cache: yes
    upgrade: safe

- name: Install Nginx, PHP-FPM, Redis, and Postfix
  apt:
    name:
      - nginx
      - php8.2-fpm
      - php8.2-mysql
      - php8.2-redis
      - php8.2-curl
      - php8.2-mbstring
      - redis-server
      - postfix
      - supervisor
    state: present

- name: Configure Nginx Virtual Host
  template:
    src: nginx.conf.j2
    dest: /etc/nginx/sites-available/default
    owner: root
    group: root
    mode: '0644'
  notify: Restart Nginx

- name: Ensure Nginx and PHP-FPM are started and enabled
  systemd:
    name: "{{ item }}"
    state: started
    enabled: yes
  loop:
    - nginx
    - php8.2-fpm
    - redis-server
    - supervisor

- name: Secure Redis configuration (bind to localhost)
  lineinfile:
    path: /etc/redis/redis.conf
    regexp: '^bind '
    line: 'bind 127.0.0.1 ::1'
  notify: Restart Redis

Langkah 6: Nginx Template (ansible/roles/web_stack/templates/nginx.conf.j2)

server {
    listen 80;
    server_name {{ app_domain }};
    root /var/www/html;

    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;

    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~* \.(jpg|jpeg|png|gif|ico|css|js|webp|svg)$ {
        expires 30d;
        add_header Cache-Control "public, no-transform";
    }

    location ~ /.ht {
        deny all;
    }
}

6. Bedah Kode & Penjelasan Detail Baris Kunci

  • Terraform backend "s3": Menyimpan status infrastruktur secara terpusat di AWS S3 dengan dukungan DynamoDB untuk state locking. Hal ini krusial dalam lingkungan tim enterprise agar dua engineer tidak melakukan terraform apply secara bersamaan yang dapat merusak file state (terraform.tfstate).
  • Cloudflare Provider proxied = true: Mengaktifkan layanan Reverse Proxy dan CDN Cloudflare di depan instance AWS. Ini memberikan proteksi DDoS otomatis, enkripsi SSL/TLS fleksibel, dan edge caching untuk meringankan beban web server.
  • Ansible become: yes: Menjalankan tugas dengan hak akses sudo (root), memastikan perintah instalasi paket OS dan modifikasi berkas sistem berjalan sukses.
  • Nginx Security Headers (X-Frame-Options, X-Content-Type-Options): Melindungi aplikasi web dari serangan Clickjacking dan MIME-type sniffing di tingkat web server sebelum request mencapai kode backend PHP/Node.js.

7. Skenario Produksi & Studi Kasus Dunia Nyata

Dalam studi kasus penanganan Flash Sale e-commerce dengan concurrency mencapai 50.000 request per detik, infrastruktur yang dibangun di atas dimodifikasi dengan pola berikut:

  1. Auto Scaling Group (ASG): Terraform mendefinisikan Launch Template alih-alih instance tunggal, dihubungkan dengan Application Load Balancer (ALB).
  2. Database Offloading: Koneksi database MySQL diarahkan ke AWS Aurora Multi-AZ dengan Read Replicas untuk membaca data katalog, sementara Redis digunakan sebagai Session Store dan Distributed Cache.
  3. Queue Processing: Worker background diatur menggunakan Supervisor yang menjalankan perintah queue consumer dari framework PHP (seperti Laravel Queue), memastikan response time HTTP tetap di bawah 100ms.

8. Common Pitfalls, Anti-Patterns & Solusi

  • Anti-Pattern 1: Menyimpan Secret di dalam Repository Git. Solusi: Selalu gunakan Terraform var sensitif dengan enkripsi, atau integrasikan HashiCorp Vault / AWS Secrets Manager. Jangan pernah melakukan commit file terraform.tfvars berisi password database.
  • Anti-Pattern 2: Tidak Mengunci Versi Provider Terraform. Solusi: Selalu tentukan versi presisi (version = "~> 5.0") pada blok required_providers untuk menghindari breaking changes dari pembaruan mayor provider pihak ketiga.
  • Pitfall 3: Menjalankan Ansible Tanpa Idempotency. Solusi: Pastikan seluruh task Ansible menggunakan modul bawaan yang bersifat idempotent (seperti apt, systemd, lineinfile) alih-alih menggunakan modul shell atau command mentah.

9. Benchmark, Metrik Kinerja & Tuning Performa

Untuk menguji ketahanan server web yang telah diprovisioning, lakukan pengujian beban menggunakan tool k6 atau wrk:

# Contoh uji beban dengan wrk (100 concurrent connections selama 30 detik)
wrk -t12 -c100 -d30s https://app.example.com/

Kernel Tuning (/etc/sysctl.conf via Ansible)

Tambahkan parameter berikut untuk mengoptimalkan performa jaringan Linux menghadapi high concurrency:

net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_tw_reuse = 1
fs.file-max = 2097152

10. Checklist Penerapan Produksi & Kesimpulan

Sebelum merilis infrastruktur ke Production, pastikan checklist berikut terpenuhi:

  • State Terraform terenkripsi dan terlindungi di S3 + DynamoDB Lock.
  • Seluruh port jaringan yang tidak perlu (sel陀了 80, 443, dan SSH terbatas) telah ditutup pada Security Group.
  • Sertifikat SSL/TLS valid terpasang (Let's Go / Cloudflare Edge Certificate).
  • Konfigurasi backup otomatis harian untuk database MySQL dan volume S3 aktif.
  • Monitoring dan alert (Prometheus + Grafana / Datadog) terhubung ke instance web dan database.

Dengan menggabungkan kekuatan deklaratif Terraform dan fleksibilitas konfigurasi Ansible, organisasi enterprise dapat mencapai level tertinggi dari Infrastructure Reliability, mempercepat time-to-market, dan menghilangkan risiko human error secara permanen.

🏷️ Tags: #Nginx #High Concurrency #Performance #Sysadmin #Web Server