summaryrefslogtreecommitdiff
path: root/ops/jenkins-api.sh
blob: 56dea93709cd3409b46f54feb1cb499a34bac68c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/env bash
# Scripted Jenkins access helper (password basic-auth is disabled on this Jenkins).
# Usage:
#   jenkins-api.sh login                 -> establishes session cookie at /tmp/opencode/.jenkins.cookie
#   jenkins-api.sh get <path>            -> authenticated GET (e.g. /job/kukuri/lastBuild/api/json)
#   jenkins-api.sh post <path>           -> authenticated POST with crumb (e.g. /job/kukuri/build)
set -euo pipefail
BASE=${JENKINS_URL:-http://localhost:8080}
USER=ketsuban
PW_FILE=/root/.jenkins_admin_pw
COOKIE=/tmp/opencode/.jenkins.cookie
PW=$(cat "$PW_FILE")

case "${1:-}" in
  login)
    rm -f "$COOKIE"
    CRUMB=$(curl -s -c "$COOKIE" "$BASE/login" | grep -oE 'name="Jenkins-Crumb" type="hidden" value="[a-f0-9]+"' | grep -oE 'value="[a-f0-9]+"' | cut -d'"' -f2)
    curl -s -c "$COOKIE" -b "$COOKIE" -o /dev/null -w "login: %{http_code}\n" \
      -d "j_username=$USER&j_password=$PW&from=%2F&Jenkins-Crumb=$CRUMB" \
      "$BASE/j_spring_security_check"
    curl -s -b "$COOKIE" "$BASE/whoAmI/api/json"
    echo ;;
  get)
    shift; exec curl -s -b "$COOKIE" "$BASE$1" ;;
  post)
    shift
    JSON=$(curl -s -b "$COOKIE" "$BASE/crumbIssuer/api/json")
    FIELD=$(echo "$JSON" | grep -oP '"crumbRequestField":\s*"\K[^"]+')
    CRUMBV=$(echo "$JSON" | grep -oP '"crumb":\s*"\K[^"]+')
    exec curl -s -b "$COOKIE" -H "$FIELD: $CRUMBV" -X POST -o /dev/null -w "%{http_code}\n" "$BASE$1" ;;
  *)
    echo "unknown command" >&2; exit 1 ;;
esac