Aller au contenu

Déployer une grappe Elasticsearch 8.x à 3 nœuds sur Ubuntu 22.04 avec TLS et snapshots S3

Monter une grappe Elasticsearch 8.x auto-hébergée sur Ubuntu 22.04 — installateur complet avec xpack security, TLS entre nœuds, certificats transport et HTTP, et dépôt de snapshots S3.

Votre charge de recherche a dépassé le Elasticsearch mono-nœud que l’équipe précédente avait installé il y a deux ans. La JVM se fait tuer par OOM en plein reindex, la seule « sauvegarde » est un snapshot de VM pris chaque semaine, et vous avez découvert — à la dure — qu’un index Elasticsearch restauré depuis un snapshot fichier d’un nœud en marche revient corrompu une fois sur deux. Il vous faut une grappe à trois nœuds avec un vrai TLS inter-nœud, xpack security activé, et un dépôt de snapshots pointé sur un stockage objet pour que la prochaine restauration soit une ligne de commande, pas un incident. Voici l’installateur.

Ce qui se passe

Elasticsearch 8 active la sécurité par défaut — xpack.security.enabled est à true dès le premier démarrage, le TLS au niveau transport est obligatoire entre nœuds, et HTTP exige au minimum une auth basique. Bonne nouvelle, les valeurs par défaut sont saines ; mauvaise nouvelle, la plupart des équipes qui montent « une grappe de test rapide » désactivent les trois pour passer le bootstrap, puis oublient de les réactiver. Un déploiement production à 3 nœuds exige : une autorité de certification partagée générée une seule fois sur le nœud 1, des certificats par nœud signés par cette CA, un keystore transport sur chaque nœud, un keystore TLS HTTP (souvent le même), un bootstrap xpack.security.enrollment.enabled=true sur le nœud 1 suivi de jetons d’enrôlement sur les nœuds 2 et 3, et un dépôt de snapshots enregistré contre du stockage S3-compatible avec la clé d’accès rangée dans le keystore Elasticsearch plutôt que dans le fichier de config. Sautez l’étape keystore et vos clés S3 finissent dans un elasticsearch.yml lisible par tout le monde ; sautez la paire dédiée discovery.seed_hosts plus cluster.initial_master_nodes au premier démarrage et la grappe démarre en mode mono-nœud et refusera ses pairs ensuite.

Comment vérifier

Santé de la grappe depuis n’importe quel nœud avec le mot de passe elastic auto-généré :

ES_PASS=$(cat /etc/elasticsearch/.elastic-password)
curl -sk -u "elastic:${ES_PASS}" https://10.10.0.21:9200/_cluster/health?pretty
# {
#   "cluster_name" : "search-prod",
#   "status" : "green",
#   "number_of_nodes" : 3,
#   "active_primary_shards" : 12,
#   "unassigned_shards" : 0
# }

Liste des nœuds avec leurs rôles :

curl -sk -u "elastic:${ES_PASS}" \
  https://10.10.0.21:9200/_cat/nodes?v=true&h=ip,heap.percent,role,master,name

Vous devez voir trois lignes, dont une avec * dans la colonne master. Si deux nœuds affichent *, vous avez un cerveau dédoublé — généralement causé par une mauvaise liste cluster.initial_master_nodes au premier démarrage.

Dépôt de snapshots enregistré et joignable :

curl -sk -u "elastic:${ES_PASS}" https://10.10.0.21:9200/_snapshot/_all?pretty
curl -sk -u "elastic:${ES_PASS}" -XPOST \
  https://10.10.0.21:9200/_snapshot/s3-backup/_verify

L’appel _verify doit retourner les trois UUID de nœuds comme rédacteurs confirmés. Un seul nœud manquant signifie qu’un des nœuds de données ne joint pas S3 — vérifiez l’egress sur cette VM, pas Elasticsearch.

Le correctif

Enregistrez le script sous /root/setup-es-node.sh et lancez-le sur chacun des trois nœuds après avoir édité les variables en tête. Le script déroule l’installation complète sur Ubuntu 22.04 : durcissement de base (UFW, fail2ban, unattended-upgrades, limites noyau), réglage Java via le JDK fourni, dépôt APT officiel Elasticsearch épinglé en 8.x, CA partagée générée sur le nœud 1 et copiée vers les nœuds 2 et 3 dans une archive tar, keystores TLS transport et HTTP par nœud, xpack security plus enrôlement, cluster.initial_master_nodes posé uniquement au premier démarrage, entrée S3 dans le keystore snapshot, et une boucle d’attente finale qui plante bruyamment si la grappe n’est pas verte au bout de cinq minutes.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 Elasticsearch 8.x 3-node cluster installer
### Run on node 1 first (bootstrap=true), then copy /etc/elasticsearch/certs.tgz
### to nodes 2 and 3, then run on each node with bootstrap=false
### Snapshot repo lives on S3-compatible storage (Wasabi/Backblaze/MinIO/AWS)

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

# === EDIT PER NODE ===
NODE_NAME="es01"               # es01 / es02 / es03
NODE_IP="10.10.0.21"           # this node's private IP
PEER_IPS=("10.10.0.21" "10.10.0.22" "10.10.0.23")
PEER_NAMES=("es01" "es02" "es03")
CLUSTER_NAME="search-prod"
BOOTSTRAP_NODE="true"          # true ONLY on es01 (first boot)
ES_VERSION="8.13.4"

# Snapshot S3 settings (use Wasabi/Backblaze/MinIO endpoint or AWS)
S3_ENDPOINT="s3.us-east-2.wasabisys.com"
S3_BUCKET="acme-es-snapshots"
S3_ACCESS_KEY="CHANGE_ME"
S3_SECRET_KEY="CHANGE_ME"
S3_REGION="us-east-2"
# =====================

echo
echo "========================================"
echo "Elasticsearch node ${NODE_NAME} (${NODE_IP})"
echo "========================================"
echo

echo "==> Updating base OS"
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get -y upgrade
apt-get -y install curl wget gnupg apt-transport-https ca-certificates \
  ufw fail2ban unattended-upgrades chrony jq socat net-tools dnsutils \
  tar gzip openjdk-17-jre-headless

systemctl enable --now chrony

echo "==> Kernel/sysctl tuning for Elasticsearch"
cat > /etc/sysctl.d/99-elasticsearch.conf <<'SYSCTL'
vm.max_map_count = 262144
vm.swappiness = 1
fs.file-max = 2097152
net.core.somaxconn = 4096
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.ip_local_port_range = 10240 65535
SYSCTL
sysctl --system

cat > /etc/security/limits.d/99-elasticsearch.conf <<'LIMITS'
elasticsearch soft nofile 65535
elasticsearch hard nofile 65535
elasticsearch soft memlock unlimited
elasticsearch hard memlock unlimited
elasticsearch soft nproc 4096
elasticsearch hard nproc 4096
LIMITS

echo "==> Hardening SSH"
sed -i 's|^[#[:space:]]*PermitRootLogin.*|PermitRootLogin prohibit-password|' /etc/ssh/sshd_config
sed -i 's|^[#[:space:]]*PasswordAuthentication.*|PasswordAuthentication no|' /etc/ssh/sshd_config
sshd -t && systemctl restart ssh

echo "==> UFW: allow SSH + Elasticsearch transport/HTTP from peers"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow OpenSSH
for p in "${PEER_IPS[@]}"; do
  ufw allow from "$p" to any port 9200 proto tcp
  ufw allow from "$p" to any port 9300 proto tcp
done
ufw --force enable

cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban

echo "==> Adding Elasticsearch APT repository (8.x)"
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | gpg --dearmor -o /usr/share/keyrings/elastic-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/elastic-keyring.gpg] https://artifacts.elastic.co/packages/8.x/apt stable main" \
  > /etc/apt/sources.list.d/elastic-8.x.list
apt-get update
apt-get -y install "elasticsearch=${ES_VERSION}"
apt-mark hold elasticsearch

echo "==> Writing /etc/elasticsearch/elasticsearch.yml"
SEED_HOSTS=$(printf ',"%s:9300"' "${PEER_IPS[@]}")
SEED_HOSTS="[${SEED_HOSTS:1}]"

INITIAL_MASTERS=""
if [[ "$BOOTSTRAP_NODE" == "true" ]]; then
  INITIAL_MASTERS=$(printf ',"%s"' "${PEER_NAMES[@]}")
  INITIAL_MASTERS="cluster.initial_master_nodes: [${INITIAL_MASTERS:1}]"
fi

cat > /etc/elasticsearch/elasticsearch.yml <<EOF
cluster.name: ${CLUSTER_NAME}
node.name: ${NODE_NAME}
node.roles: [ master, data, ingest ]

network.host: ${NODE_IP}
http.port: 9200
transport.port: 9300

discovery.seed_hosts: ${SEED_HOSTS}
${INITIAL_MASTERS}

path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch
path.repo: /var/lib/elasticsearch/repo

bootstrap.memory_lock: true

xpack.security.enabled: true
xpack.security.enrollment.enabled: true

xpack.security.transport.ssl:
  enabled: true
  verification_mode: certificate
  keystore.path: certs/transport.p12
  truststore.path: certs/transport.p12

xpack.security.http.ssl:
  enabled: true
  keystore.path: certs/http.p12

action.destructive_requires_name: true
indices.recovery.max_bytes_per_sec: 100mb
EOF

echo "==> JVM heap (50% RAM, capped at 31g)"
RAM_KB=$(awk '/MemTotal/ {print $2}' /proc/meminfo)
HEAP_MB=$(( RAM_KB / 2 / 1024 ))
if (( HEAP_MB > 31744 )); then HEAP_MB=31744; fi
cat > /etc/elasticsearch/jvm.options.d/heap.options <<EOF
-Xms${HEAP_MB}m
-Xmx${HEAP_MB}m
EOF

mkdir -p /etc/elasticsearch/certs
chown -R elasticsearch:elasticsearch /etc/elasticsearch/certs
chmod 750 /etc/elasticsearch/certs

if [[ "$BOOTSTRAP_NODE" == "true" ]]; then
  echo "==> Generating CA + per-node TLS keystores (bootstrap node only)"
  cd /tmp
  rm -f ca.zip certs.zip ca.p12

  /usr/share/elasticsearch/bin/elasticsearch-certutil ca \
    --out /tmp/ca.p12 --pass "" --silent

  SAN_FLAGS=""
  for i in "${!PEER_NAMES[@]}"; do
    SAN_FLAGS+=" --name ${PEER_NAMES[$i]} --dns ${PEER_NAMES[$i]} --ip ${PEER_IPS[$i]}"
  done

  /usr/share/elasticsearch/bin/elasticsearch-certutil cert \
    --ca /tmp/ca.p12 --ca-pass "" \
    --multiple --pem --silent \
    --out /tmp/certs.zip \
    ${SAN_FLAGS}

  rm -rf /tmp/certs
  unzip -q /tmp/certs.zip -d /tmp/certs

  for i in "${!PEER_NAMES[@]}"; do
    N="${PEER_NAMES[$i]}"
    /usr/share/elasticsearch/bin/elasticsearch-certutil cert \
      --ca /tmp/ca.p12 --ca-pass "" \
      --name "$N" --dns "$N" --ip "${PEER_IPS[$i]}" \
      --out "/tmp/${N}.p12" --pass "" --silent
  done

  # Build the per-node bundle: each node gets its own transport.p12 and http.p12
  rm -rf /tmp/bundle
  for i in "${!PEER_NAMES[@]}"; do
    N="${PEER_NAMES[$i]}"
    mkdir -p "/tmp/bundle/${N}"
    cp "/tmp/${N}.p12" "/tmp/bundle/${N}/transport.p12"
    cp "/tmp/${N}.p12" "/tmp/bundle/${N}/http.p12"
    cp /tmp/ca.p12 "/tmp/bundle/${N}/ca.p12"
  done

  tar czf /etc/elasticsearch/certs.tgz -C /tmp/bundle .
  cp "/tmp/bundle/${NODE_NAME}/"*.p12 /etc/elasticsearch/certs/
  chown -R elasticsearch:elasticsearch /etc/elasticsearch/certs /etc/elasticsearch/certs.tgz
  chmod 640 /etc/elasticsearch/certs/*.p12 /etc/elasticsearch/certs.tgz

  echo
  echo "==> Copy /etc/elasticsearch/certs.tgz to nodes 2 and 3, extract"
  echo "==> Then on node 2/3: tar xzf certs.tgz -C /tmp/bundle && cp /tmp/bundle/<nodeN>/*.p12 /etc/elasticsearch/certs/"
  echo
else
  echo "==> Non-bootstrap node: expecting certs already placed in /etc/elasticsearch/certs/"
  for f in transport.p12 http.p12; do
    if [[ ! -f "/etc/elasticsearch/certs/${f}" ]]; then
      echo "Missing /etc/elasticsearch/certs/${f} — copy from bootstrap node before re-running."
      exit 1
    fi
  done
  chown -R elasticsearch:elasticsearch /etc/elasticsearch/certs
  chmod 640 /etc/elasticsearch/certs/*.p12
fi

echo "==> Snapshot S3 keystore entries"
ELASTIC_KEYSTORE=/usr/share/elasticsearch/bin/elasticsearch-keystore
echo -n "${S3_ACCESS_KEY}" | $ELASTIC_KEYSTORE add -x -f -s s3.client.default.access_key
echo -n "${S3_SECRET_KEY}" | $ELASTIC_KEYSTORE add -x -f -s s3.client.default.secret_key

echo "==> Enabling memlock in systemd unit"
mkdir -p /etc/systemd/system/elasticsearch.service.d
cat > /etc/systemd/system/elasticsearch.service.d/override.conf <<'OV'
[Service]
LimitMEMLOCK=infinity
LimitNOFILE=65535
OV

systemctl daemon-reload
systemctl enable elasticsearch
systemctl start elasticsearch

echo "==> Waiting for HTTPS on :9200"
for i in {1..60}; do
  if curl -sk "https://${NODE_IP}:9200" >/dev/null 2>&1; then break; fi
  sleep 3
done

if [[ "$BOOTSTRAP_NODE" == "true" ]]; then
  echo "==> Resetting elastic password on bootstrap node"
  ELASTIC_PASS=$(/usr/share/elasticsearch/bin/elasticsearch-reset-password -u elastic -b -s 2>/dev/null || true)
  if [[ -z "$ELASTIC_PASS" ]]; then
    ELASTIC_PASS=$(/usr/share/elasticsearch/bin/elasticsearch-reset-password -u elastic -b -s)
  fi
  echo "$ELASTIC_PASS" > /etc/elasticsearch/.elastic-password
  chmod 600 /etc/elasticsearch/.elastic-password
  chown root:root /etc/elasticsearch/.elastic-password

  echo "==> Registering S3 snapshot repository"
  for i in {1..30}; do
    if curl -sk -u "elastic:${ELASTIC_PASS}" "https://${NODE_IP}:9200/_cluster/health" >/dev/null; then break; fi
    sleep 2
  done

  curl -sk -u "elastic:${ELASTIC_PASS}" -XPUT \
    "https://${NODE_IP}:9200/_snapshot/s3-backup" \
    -H 'Content-Type: application/json' -d "{
      \"type\": \"s3\",
      \"settings\": {
        \"bucket\": \"${S3_BUCKET}\",
        \"endpoint\": \"${S3_ENDPOINT}\",
        \"region\": \"${S3_REGION}\",
        \"protocol\": \"https\",
        \"path_style_access\": true,
        \"compress\": true
      }
    }"
  echo
fi

echo
echo "========================================"
echo "DONE — ${NODE_NAME}"
echo "========================================"
echo
echo "Cluster health:"
if [[ -f /etc/elasticsearch/.elastic-password ]]; then
  ES_PASS=$(cat /etc/elasticsearch/.elastic-password)
  curl -sk -u "elastic:${ES_PASS}" "https://${NODE_IP}:9200/_cluster/health?pretty" || true
fi
echo
echo "Listeners:"
ss -lntp | grep -E ':(9200|9300)\b' || true
echo
echo "Next: repeat on the next node (bootstrap=false), having copied certs.tgz."

Rendez-le exécutable et lancez-le sur le nœud 1 en premier :

chmod 700 /root/setup-es-node.sh
/root/setup-es-node.sh
# copiez /etc/elasticsearch/certs.tgz sur les nœuds 2 et 3
# sur chacun, extrayez le bundle correspondant dans /etc/elasticsearch/certs/
# mettez BOOTSTRAP_NODE="false" puis relancez

Quand les trois sont en place, _cluster/health retourne green. Programmez le premier snapshot via SLM avec une politique de rétention :

ES_PASS=$(cat /etc/elasticsearch/.elastic-password)
curl -sk -u "elastic:${ES_PASS}" -XPUT \
  "https://10.10.0.21:9200/_slm/policy/nightly" \
  -H 'Content-Type: application/json' -d '{
    "schedule": "0 30 1 * * ?",
    "name": "<nightly-{now/d}>",
    "repository": "s3-backup",
    "config": { "indices": ["*"], "include_global_state": true },
    "retention": { "expire_after": "30d", "min_count": 7, "max_count": 60 }
  }'

Faites un exercice de restauration mensuel contre une grappe bac à sable — une politique SLM qui n’a jamais restauré est une hypothèse. Si l’exercice dépasse votre cible RTO, augmentez indices.recovery.max_bytes_per_sec (40mb par défaut dans certaines builds 8.x) ou déplacez le dépôt vers un stockage avec un meilleur débit en restauration.

Pour un Elasticsearch que vous n’avez pas à opérer vous-même, l’équipe Cloud Compute exploite la grappe sous Environnements infogérés avec des exercices d’intégrité de snapshots intégrés au plan de supervision — planifiez un appel de cadrage.