Jenkins 빌드의 원격 트리거를 수행 할 때“화재하고 잊어 버리지”않는 방법은 무엇입니까?


13

Bamboo에서 매개 변수화 된 Jenkins 빌드를 트리거하려고 시도 중입니다.

우편 - http://jenkins-url.com/job/jobname/buildWithParameters?ENVIRONMENT=dev&APPLICATION=hello-world

그러나 빌드가 생성되었음을 알려주는 201을 즉시 얻을 것입니다. 이 요청을 기다리지 않고 빌드의 성공 상태를 반환하고 잊어 버리는 방법은 무엇입니까?

Parameterized-Remote-Trigger-Plugin에 따라 분명히 가능합니다 .

여기에 이미지 설명을 입력하십시오

편집 : 필요한 경우이를 생성했습니다. https://github.com/owenmorgan/jenkins-remote-builder

답변:


5

원격 트리거를 설정할 때 "원격 트리거 된 프로젝트가 빌드를 완료 할 때까지 차단"을 클릭해야합니다.

원격 매개 변수화 된 작업


고마워, 스틱의 끝이 잘못되었을 수 있습니다. 플러그인이 젠킨스 자체에서 원격 빌드를 트리거하기위한 것 같습니다. 필자의 시나리오에서는 Bamboo의 요청에서 빌드가 트리거되지만 빌드가 완료되고 빌드 상태를 반환 할 때까지 해당 요청을 보류하고 싶습니다.
osmorgan

아, 이제 이해합니다. 불행히도 API가 그렇게 작동하지 않는다고 생각합니다. Jenkins 용 플러그인이 어떻게 개발되는지 보면 원격 작업을 트리거 한 다음 완료 될 때까지 상태를 폴링합니다.
트래비스 톰슨

1
덕분에, 나는이 만들고 결국 github.com/owenmorgan/jenkins-remote-builder을
osmorgan

1
@osmorgan : 당신은 대답 (링크뿐만 아니라 약간의 요약으로)을 설명하고 받아 들여야합니다.
Dan Cornilescu

sheesh .. 질문에 .. 그리고 링크에 설명이 있습니다. stackoverflow에서 보자.
osmorgan

5

내가 만든 젠킨스 - 원격 빌더 완료 원격 빌드를 수행 할 스크립트를.

이에 대한 자세한 내용은 ( README.md에서 ) :

jenkins=https://user:pass@jenkins.mydomain.com:8080
jenkins_job=MyApp-Deploy

environment=dev
application=myapp
revision=9fd71f63b351b8208264daf86d292ced580a2f60

./jenkins_remote_trigger.sh \
            -h ${jenkins} \
            -j ${jenkins_job} \
            -p "ENVIRONMENT=${environment}&APPLICATION=${application}&REVISION=${revision}"

용법:

-h HOST     | --host=HOST                       Jenkins host
-j JOBNAME  | --jobname=test-build-job          The name of the jenkins job to trigger
-p JOBPARAM | --jobparam=environment=uat&test=1 Jenkins job paramiters
-q          | --quiet                           Don't output any status messages

4
작동 방식에 대한 약간의 요약이 더 좋을 것입니다.)
Tensibai

귀하의 (재미있는!) 답변에 적용한 편집 내용을 검토하십시오. 그러나 링크에 대한 답변이기 때문에 (중간을 통해) 삭제 될 위험이 있다고 생각합니다 (@ Tensibai의 의견에 의해 표시됨) ).
Pierre.Vriens

1

CLI에서 작업을 트리거하고 완료 될 때까지 기다려야하는 경우 "Jenkins CLI"를 사용할 수 있습니다 ( 여기 참조 ).

그러나 jenkins CLI는 프로모션을 지원하지 않으므로 프로모션을 위해 다음 스크립트를 생각해 냈습니다.

#!/bin/bash
# Trigger a promotion and wait for its completion
#
# For triggering jobs jenkins cli is sufficient: https://support.cloudbees.com/hc/en-us/articles/228392127-How-to-wait-for-build-to-finish-when-triggering-from-CLI-
#
# The script is dependent on the current jenkins implementation of:
# - the promotion web page (links for triggering/re-executing the promotions)
# - the behaviour of the XML of the promotion status
#
# The behaviour of the job run status XML is:
#   - if the the promotion is not yet been triggered than the response is 404 not found
#   - is the the promotion has been triggered
#     - ... but it's still waiting for an executor:  the response is 404 not found or <duration> is empty
#     - ... and has started:                         <duration> is empty or 0
#     - ... and it's finished:                       <duration> is a non-zero number
#
#
#  run syntax:
#    ./trigger_promotion_and_wait_for_completion.sh \
#       <job_name> \
#       <job_run_number_to_promote> \
#       <promotion_name> \
#       <jenkins_user> \
#       <jenkins_pwd> \
#       <jenkins_url> \
#       <script_workspace_folder> \
#       '{"name": "prom_param_1", "value": "stringvalue" } , {"name": "prom_param_2", "value": true }'
#
#   example:
#    ./trigger_promotion_and_wait_for_completion.sh \
#       job1 \
#       22 \
#       promotion1 \
#       admin \
#       password \
#       http://localhost:8080/jenkins/ \
#       . \
#       '{"name": "prom_param_1", "value": "stringvalue" } , {"name": "prom_param_2", "value": true }'



set -uexo pipefail

#other debug options:
#PS4='+\t '
#set -v

JOB_NAME="${1}"
JOB_RUN_NUMBER="${2}"
DEPLOY_PROMOTION_NAME="${3}"
BUILDER_USER="${4}"
BUILDER_PASSWORD="${5}"
JENKINS_URL="${6}"
WORKSPACE_FOLDER="${7}"
PROMOTION_ARGUMENTS="${8}"

TIMEOUT=900


echo "retrieving the promotion nextBuildNumber (so we can poll the promotion status and check if it's finished)..."
PROMOTION_RUN_NUMBER="$( curl -s  -u${BUILDER_USER}:${BUILDER_PASSWORD} "${JENKINS_URL}job/${JOB_NAME}/promotion/process/${DEPLOY_PROMOTION_NAME}/api/xml"  | grep -P  '<nextBuildNumber>(.*)</nextBuildNumber'   | sed -re 's/.*<nextBuildNumber>(.*)<\/nextBuildNumber.*/\1/g' )"




echo "running the promotion..."
echo 'only the first promotion can be triggered with "Approve", while subsequent promotions are triggered with "Re-execute promotion"'
echo 'so we check in the web page if the approve link is present'

#the link to search in the web page
PROMOTION_APPROVE_STRING="promotionProcess/${DEPLOY_PROMOTION_NAME}/promotionCondition/hudson.plugins.promoted_builds.conditions.ManualCondition/approve"

PROM_STATUS_URL="${JENKINS_URL}job/${JOB_NAME}/${JOB_RUN_NUMBER}/promotion/"

if curl -s -vvv -u${BUILDER_USER}:${BUILDER_PASSWORD}  "${PROM_STATUS_URL}" | grep "${PROMOTION_APPROVE_STRING}" ; then
    echo "The job has not yet been promoted, triggering it with 'Approve'"
    WEB_PATH="job/${JOB_NAME}/${JOB_RUN_NUMBER}/promotion/promotionProcess/${DEPLOY_PROMOTION_NAME}/promotionCondition/hudson.plugins.promoted_builds.conditions.ManualCondition/approve"
    SUBMIT="Approve"
else
    echo "The job has already been promoted, triggering it with 'Re-execute promotion'"
    WEB_PATH="job/${JOB_NAME}/${JOB_RUN_NUMBER}/promotion/${DEPLOY_PROMOTION_NAME}/build"
    SUBMIT="Re-execute+promotion"
fi


#note for the troubleshooting: in case the following curl fails then the error cause can be found near the string "stack trace"
CURL_OUTPUT="$(  curl -s -vvv -XPOST -u${BUILDER_USER}:${BUILDER_PASSWORD} "${JENKINS_URL}${WEB_PATH}"  \
                       --data 'json={
                                 "parameter": [
                                                '"${PROMOTION_ARGUMENTS}"'
                                              ]
                                    }&Submit='"${SUBMIT}" 2>&1 )"

if ( echo "${CURL_OUTPUT}" |  grep -P "< HTTP/1.1 5\d\d" ) || ( echo "${CURL_OUTPUT}" |  grep -P "< HTTP/1.1 4\d\d" ) ; then
  echo  'error in triggering the job/promotion! exiting...'
  exit 1
else
  echo  'curl good'
fi



echo "checking promotion status until promotion is finished"
FINISHED=no


INITIAL_TIME="$(date +%s)"
while [ "${FINISHED}" != "ok" ]
do
    sleep 2


    #checking if promotion is finished (we check the value of <duration> XML element in the job run status)
    ERROR="" ; DURATION="$(curl -s  -u${BUILDER_USER}:${BUILDER_PASSWORD} "${JENKINS_URL}job/${JOB_NAME}/${JOB_RUN_NUMBER}/promotion/${DEPLOY_PROMOTION_NAME}/promotionBuild/${PROMOTION_RUN_NUMBER}/api/xml"    | grep -Po  '<duration>.*</duration>'   | sed -re  's/<duration>(.*)<\/duration>/\1/g' )"   || ERROR="yes"
    if [[ $ERROR == "yes" ]] ; then
      echo " the promotion has been queued but not yet started, waiting for it to start..."
      curl -s  -u${BUILDER_USER}:${BUILDER_PASSWORD} "${JENKINS_URL}job/${JOB_NAME}/${JOB_RUN_NUMBER}/promotion/${DEPLOY_PROMOTION_NAME}/promotionBuild/${PROMOTION_RUN_NUMBER}/api/xml"
      ERROR=""
      continue
    fi  ;   ERROR=""




    #we interrupt the polling of the job/promotion status if the promotion
    #  - is terminated
    #  - is taking too long (there is some problem)
    #(in the XML of the job run status the <duration> XML element value is initially empty, than it is 0, and eventually is the number of seconds of the run duration )

    POLLING_TIME="$(date +%s)"
    let "ELAPSED_TIME=POLLING_TIME-INITIAL_TIME"
    echo "ELAPSED_TIME=${ELAPSED_TIME}"

    if  (( ${ELAPSED_TIME} \> $TIMEOUT ))  ; then
      echo "error: the promotion has taken too long... exiting"
      exit 1
    fi

    if  [[ "${DURATION}" != "" ]] ; then
      re='^[0-9]+$'
      if [[ $DURATION =~ $re ]] ; then
        if (( "${DURATION}" \> "0" )) ; then
          FINISHED=ok
        else
          : #do nothing (the value of <duration> is 0 , that is the job/promotion has been started in a slave and is still running)
        fi
      else
        echo "error: the promotion duration is not a number. exiting..."
        exit 1
      fi
    else
      :  # the job/promotion has not yet started
    fi

    echo "waiting for the promotion to finish..."
done

echo "Promotion finished"



echo "Promotion output:"
curl -s  -u${BUILDER_USER}:${BUILDER_PASSWORD} "${JENKINS_URL}job/${JOB_NAME}/${JOB_RUN_NUMBER}/promotion/${DEPLOY_PROMOTION_NAME}/promotionBuild/${PROMOTION_RUN_NUMBER}/consoleText" > ${WORKSPACE_FOLDER}/promotionOutput

cat ${WORKSPACE_FOLDER}/promotionOutput

if [[ ! "$(tail -n1 ${WORKSPACE_FOLDER}/promotionOutput)" =~ "SUCCESS"  ]] ; then
      echo "Promotion did not successfully terminate"
      exit 1
else
      echo "Promotion successfully terminated"
fi
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.