generate.sh 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/bin/sh
  2. # This script will generate Jenkins jobs in YAML format, so you could
  3. # use "jenkins-jobs" program to operate them as described in
  4. # https://docs.openstack.org/infra/jenkins-job-builder/project_workflow_multibranch.html
  5. #
  6. # The script requires curl, jq, yq programs.
  7. # Tested on Jenkins 2.204.1.
  8. #
  9. # You should set JENKINS_URL and CURL_USER to your credentials, then
  10. # run the script, e.g. ./generate.sh
  11. JENKINS_URL="https://jenkins.wugi.info"
  12. CURL_USER="admin:$(pass show jenkins/admin-api-key)"
  13. jenkins_curl()
  14. {
  15. curl --silent --user "$CURL_USER" "$@"
  16. }
  17. folders()
  18. {
  19. jenkins_curl --request POST "$JENKINS_URL/api/json"
  20. }
  21. jobs()
  22. {
  23. folder="$1"
  24. jenkins_curl --request POST "$JENKINS_URL/job/$folder/api/json"
  25. }
  26. job()
  27. {
  28. folder="$1"
  29. job="$2"
  30. jenkins_curl --request GET "$JENKINS_URL/job/$folder/job/$job/api/json"
  31. }
  32. giturl()
  33. {
  34. folder="$1"
  35. job="$2"
  36. jenkins_curl --request GET "$JENKINS_URL/job/$folder/job/$job/config.xml"
  37. }
  38. main()
  39. {
  40. # shellcheck disable=SC2016
  41. for folder in $(folders | jq --raw-output '.jobs[] | .name'); do
  42. echo "$folder" | yq --yaml-output --arg FOLDER "$folder" '[{"job": {"name": $FOLDER, "project-type": "folder"}}]'
  43. for job in $(jobs "$folder" | jq --raw-output '.jobs[] | .name'); do
  44. giturl=$(giturl "$folder" "$job" | xq --raw-output '.["org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject"].sources.data["jenkins.branch.BranchSource"].source.remote')
  45. job "$folder" "$job" | yq --arg GITURL "$giturl" --arg FOLDER "$folder" --arg JOB "$job" --yaml-output '[.jobs[] | {"job": { "name": "\($FOLDER)/\($JOB)", description: null, "project-type": "multibranch", "periodic-folder-trigger": "1d", "prune-dead-branches": true, "number-to-keep": "10", "days-to-keep": "10", "script-path": "Jenkinsfile", "scm": [{"git": {"url": $GITURL}}]}}]'
  46. done
  47. done
  48. }
  49. # Entry point
  50. main