Files
Genarrative/scripts/deploy/jenkins-inbound-agent-start.sh
kdletters 01b302d7eb
Some checks failed
CI / verify (push) Has been cancelled
Add resilient Jenkins inbound agent setup
2026-05-03 14:01:19 +08:00

81 lines
2.3 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat >&2 <<'EOF'
用法:
jenkins-inbound-agent-start <agent-name>
说明:
该脚本由 systemd 调用,读取 /etc/jenkins-agent/<agent-name>.env
下载 Jenkins agent.jar并通过 inbound WebSocket 连接 Jenkins controller。
EOF
}
AGENT_INSTANCE="${1:-}"
if [[ -z "${AGENT_INSTANCE}" ]]; then
usage
exit 2
fi
CONFIG_FILE="${JENKINS_AGENT_CONFIG_FILE:-/etc/jenkins-agent/${AGENT_INSTANCE}.env}"
if [[ ! -r "${CONFIG_FILE}" ]]; then
echo "[jenkins-agent] 配置文件不可读: ${CONFIG_FILE}" >&2
exit 1
fi
set -a
# shellcheck disable=SC1090
source "${CONFIG_FILE}"
set +a
JENKINS_AGENT_NAME="${JENKINS_AGENT_NAME:-${AGENT_INSTANCE}}"
JENKINS_AGENT_WORKDIR="${JENKINS_AGENT_WORKDIR:-/var/lib/jenkins/agent/${JENKINS_AGENT_NAME}}"
JENKINS_AGENT_JAR="${JENKINS_AGENT_JAR:-/opt/jenkins-agent/agent.jar}"
JENKINS_AGENT_SECRET_FILE="${JENKINS_AGENT_SECRET_FILE:-/etc/jenkins-agent/${JENKINS_AGENT_NAME}.secret}"
JENKINS_AGENT_USE_WEBSOCKET="${JENKINS_AGENT_USE_WEBSOCKET:-true}"
JENKINS_AGENT_JAVA_BIN="${JENKINS_AGENT_JAVA_BIN:-java}"
if [[ -z "${JENKINS_URL:-}" ]]; then
echo "[jenkins-agent] JENKINS_URL 不能为空。" >&2
exit 1
fi
if [[ -z "${JENKINS_AGENT_SECRET:-}" ]]; then
if [[ ! -r "${JENKINS_AGENT_SECRET_FILE}" ]]; then
echo "[jenkins-agent] 未提供 JENKINS_AGENT_SECRET且密钥文件不可读: ${JENKINS_AGENT_SECRET_FILE}" >&2
exit 1
fi
JENKINS_AGENT_SECRET="$(tr -d '\r\n' <"${JENKINS_AGENT_SECRET_FILE}")"
fi
if [[ -z "${JENKINS_AGENT_SECRET}" ]]; then
echo "[jenkins-agent] Jenkins inbound agent secret 不能为空。" >&2
exit 1
fi
mkdir -p "$(dirname "${JENKINS_AGENT_JAR}")" "${JENKINS_AGENT_WORKDIR}"
AGENT_JAR_URL="${JENKINS_URL%/}/jnlpJars/agent.jar"
AGENT_JAR_TMP="${JENKINS_AGENT_JAR}.tmp"
echo "[jenkins-agent] 下载 agent.jar: ${AGENT_JAR_URL}"
curl -fsSL --retry 5 --retry-delay 5 "${AGENT_JAR_URL}" -o "${AGENT_JAR_TMP}"
mv "${AGENT_JAR_TMP}" "${JENKINS_AGENT_JAR}"
agent_args=(
"${JENKINS_AGENT_JAVA_BIN}"
-jar "${JENKINS_AGENT_JAR}"
-url "${JENKINS_URL}"
-secret "${JENKINS_AGENT_SECRET}"
-name "${JENKINS_AGENT_NAME}"
-workDir "${JENKINS_AGENT_WORKDIR}"
)
if [[ "${JENKINS_AGENT_USE_WEBSOCKET}" == "true" ]]; then
agent_args+=(-webSocket)
fi
echo "[jenkins-agent] 启动 inbound agent: ${JENKINS_AGENT_NAME}"
exec "${agent_args[@]}"