Programing

Git post commit hook 설정 방법

lottogame 2020. 7. 13. 08:09
반응형

Git post commit hook 설정 방법


Jenkins에서 원격으로 빌드를 트리거하는 방법은 무엇입니까?
Git post commit hook을 설정하는 방법?

내 요구 사항은 특정 프로젝트에 대한 Git 저장소에서 변경이 이루어질 때마다 해당 프로젝트에 대해 Jenkins 빌드를 자동으로 시작하는 것입니다.

Jenkins 트리거 빌드 섹션에서 원격으로 트리거 빌드를 선택했습니다.
에서 .git디렉토리, 디렉토리가 우리가 구성 포스트에 가지고있는 파일을 커밋 후크.
거기에서 빌드를 트리거하는 방법을 혼란스럽게 생각합니다 (컬 명령을 사용해야한다는 것을 알고 있습니다).


curl cmbuild.aln.com/jenkins/view/project name/job/myproject/buildwithparameters?Branch=feat-con

이 명령을 git server hooks 디렉토리 (post commit hook)에 넣었습니다.
저장소에서 변경이 발생할 때마다 자동화 빌드가 실행됩니다.

적어도 하나의 Java 파일에 빌드가 시작되는지 변경 세트를 확인하고 싶습니다.
개발자가 빌드를 시작하지 않아야하는 xml 파일 또는 특성 파일 만 변경했다고 가정하십시오.
와 함께 파일이 빌드가 시작되어야 xml한다고 가정합니다 .java.


" 폴링은 반드시 죽어야합니다 : Jenkins 빌드를 git hook에서 트리거하기 "에서 언급했듯이 Jenkins 에게 새로운 커밋을 알릴 수 있습니다.

최신 Git 플러그인 1.1.14 (지금 막 릴리스)를 사용하면 다음 명령을 간단히 실행하여보다 쉽게이 작업을 수행 할 수 있습니다.

curl http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>

지정된 URL을 체크 아웃하도록 구성된 모든 작업을 스캔하고 폴링으로 구성된 경우 즉시 폴링을 트리거합니다 (빌드 할 가치가있는 변경 사항이 발견되면 빌드가 차례로 트리거 됨). )

이것은 젠킨스에서 일자리가왔다 갔다 할 때 스크립트가 동일하게 유지되도록합니다.
또는 단일 리포지토리 호스트 응용 프로그램 (예 : Gitosis)에 여러 리포지토리가있는 경우 모든 리포지토리와 단일 수신 후 후크 스크립트를 공유 할 수 있습니다. 마지막으로,이 URL은 보안 Jenkins에 대해서도 인증이 필요하지 않습니다. 서버는 클라이언트가 전송하는 것을 직접 사용하지 않기 때문입니다. 실제로 빌드를 시작하기 전에 변경 사항이 있는지 확인하기 위해 폴링을 실행합니다.

으로 여기에 언급 , 당신 젠킨스 서버에 대한 올바른 주소를 사용해야합니다 :

포트 8080에서 독립형 웹 서버로 Jenkins를 실행하고 있기 때문에 URL은 다음 /jenkins과 같이 없어야 합니다.

http://jenkins:8080/git/notifyCommit?url=git@gitserver:tools/common.git

그 마지막 요점을 강화하기 위해 ptha주석을 추가합니다 .

명백 할 수도 있지만 다음과 같은 문제가 있습니다.

curl http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>. 

URL의 매개 변수는이 무엇인지 정확히 일치해야합니다 저장소 URL 당신의 젠킨스 작업.
예제를 복사 할 때 프로토콜을 생략했지만 ssh://작동하지 않았습니다.


또한 간단한 사용할 수 있습니다 "처럼 후크를 포스트 - 수신 기반 푸시 젠킨스와 GIT를 사용하여 구축 "

#!/bin/bash
/usr/bin/curl --user USERNAME:PASS -s \

http://jenkinsci/job/PROJECTNAME/build?token=1qaz2wsx

"원격으로 빌드 트리거"및 인증 토큰 ( 1qaz2wsx이 예에서는) 을 사용할 수 있도록 Jenkins 작업을 구성하십시오 .

However, this is a project-specific script, and the author mentions a way to generalize it.
The first solution is easier as it doesn't depend on authentication or a specific project.


I want to check in change set whether at least one java file is there the build should start.
Suppose the developers changed only XML files or property files, then the build should not start.

Basically, your build script can:

  • put a 'build' notes (see git notes) on the first call
  • on the subsequent calls, grab the list of commits between HEAD of your branch candidate for build and the commit referenced by the git notes 'build' (git show refs/notes/build): git diff --name-only SHA_build HEAD.
  • your script can parse that list and decide if it needs to go on with the build.
  • in any case, create/move your git notes 'build' to HEAD.

May 2016: cwhsu points out in the comments the following possible url:

you could just use curl --user USER:PWD http://JENKINS_SERVER/job/JOB_NAME/build?token=YOUR_TOKEN if you set trigger config in your item

http://i.imgur.com/IolrOOj.png


June 2016, polaretto points out in the comments:

I wanted to add that with just a little of shell scripting you can avoid manual url configuration, especially if you have many repositories under a common directory.
For example I used these parameter expansions to get the repo name

repository=${PWD%/hooks}; 
repository=${repository##*/} 

and then use it like:

curl $JENKINS_URL/git/notifyCommit?url=$GIT_URL/$repository

Hope this helps: http://nrecursions.blogspot.in/2014/02/how-to-trigger-jenkins-build-on-git.html

It's just a matter of using curl to trigger a Jenkins job using the git hooks provided by git.
The command

curl http://localhost:8080/job/someJob/build?delay=0sec

can run a Jenkins job, where someJob is the name of the Jenkins job.

Search for the hooks folder in your hidden .git folder. Rename the post-commit.sample file to post-commit. Open it with Notepad, remove the : Nothing line and paste the above command into it.

That's it. Whenever you do a commit, Git will trigger the post-commit commands defined in the file.


As the previous answer did show an example of how the full hook might look like here is the code of my working post-receive hook:

#!/usr/bin/python

import sys
from subprocess import call

if __name__ == '__main__':
    for line in sys.stdin.xreadlines():
        old, new, ref = line.strip().split(' ')
        if ref == 'refs/heads/master':
            print "=============================================="
            print "Pushing to master. Triggering jenkins.        "
            print "=============================================="
            sys.stdout.flush()
            call(["curl", "-sS", "http://jenkinsserver/git/notifyCommit?url=ssh://user@gitserver/var/git/repo.git"])

In this case I trigger jenkins jobs only when pushing to master and not other branches.


I want to add to the answers above that it becomes a little more difficult if Jenkins authorization is enabled.

After enabling it I got an error message that anonymous user needs read permission.

I saw two possible solutions:

1: Changing my hook to:

curl --user name:passwd -s http://domain?token=whatevertokenuhave

2: setting project based authorization.

The former solutions has the disadvantage that I had to expose my passwd in the hook file. Unacceptable in my case.

The second works for me. In the global auth settings I had to enable Overall>Read for Anonymous user. In the project I wanted to trigger I had to enable Job>Build and Job>Read for Anonymous.

This is still not a perfect solution because now you can see the project in Jenkins without login. There might be an even better solution using the former approach with http login but I haven't figured it out.

참고URL : https://stackoverflow.com/questions/12794568/how-to-configure-git-post-commit-hook

반응형