#!/bin/bash set -euo pipefail AWS_REGION="ap-southeast-7" SSM_PREFIX="/amrez/eop" need() { aws ssm get-parameter --with-decryption --region "$AWS_REGION" --name "${SSM_PREFIX}/$1" \ --query "Parameter.Value" --output text } # autossh if ! command -v autossh >/dev/null 2>&1; then dnf install -y autossh >/dev/null fi SSH_USER=$(need "tunnel/ssh_user") BASTION_HOST=$(need "tunnel/bastion_host") DB_HOST=$(need "tunnel/db_host") DB_PORT=$(need "tunnel/db_port") LOCAL_PORT=$(need "tunnel/local_port") install -d -m 700 -o root -g root /opt/eop-tunnel aws ssm get-parameter --with-decryption --region "$AWS_REGION" \ --name "${SSM_PREFIX}/tunnel/private_key" --query "Parameter.Value" --output text > /opt/eop-tunnel/id_rsa chmod 600 /opt/eop-tunnel/id_rsa cat >/etc/systemd/system/eop-db-tunnel.service < ${DB_HOST}:${DB_PORT} via ${BASTION_HOST}) After=network-online.target Wants=network-online.target [Service] Type=simple User=root Restart=always RestartSec=5 ExecStartPre=/usr/bin/bash -lc 'ss -lnt | grep -q ":${LOCAL_PORT} " && killall -q -w ssh || true' ExecStart=/usr/bin/autossh -M 0 -N \ -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -o ExitOnFailure=yes -o ExitOnForwardFailure=yes \ -o StrictHostKeyChecking=no -i /opt/eop-tunnel/id_rsa \ -L 127.0.0.1:${LOCAL_PORT}:${DB_HOST}:${DB_PORT} ${SSH_USER}@${BASTION_HOST} [Install] WantedBy=multi-user.target EOF systemctl daemon-reload systemctl enable --now eop-db-tunnel.service # wait ready for i in {1..30}; do ss -lnt | grep -q ":${LOCAL_PORT} " && exit 0 sleep 1 done echo "Tunnel not ready on 127.0.0.1:${LOCAL_PORT}" >&2 exit 1