Jenkins + Github 연동
# Jenkins # Github # push event # hook
이번 포스트에서는 Jenkins와 Github을 연동하는 방법에 대해 다룬다. 연동했을 때의 장점은 Github의 commit, push, pull request 등의 이벤트가 발생할 때, 자동으로 테스팅과 함께 빌드를 하여 프로그램의 통합시간을 크게 단축시킬 수 있다.
프로젝트 준비
Jenkins 설정
먼저 Jenkins에서 새 프로젝트를 생성한다. Freestyle project로 생성한다.

아래 이미지와 같이 Github project의 주소를 복사하여 입력하고, 소스코드 관리 또한 [Git] - [git주소입력] 후, Credentials 설정을 위해 [add 버튼] - [jenkins]를 누른다.

Username에는 Github의 계정ID, Password에는 Github 계정 비밀번호를 입력하고 Add 버튼을 누른다.

[빌드 유발] 탭에서는 GitHub hook trigger for GITScm polling 을 누른다. Github의 hook trigger를 이용해 빌드를 유발시킬 것이다.

밑에 주의사항이 생길 수 있다. 지금은 github에서 아무 설정도 하지 않았기 때문에 연결을 하라고 하는 메시지이다. 지금은 무시하자.

위 프로젝트 준비에서 fork한 프로젝트는 Maven으로 빌드할 수 있다. 그리고 몇 가지 테스트가 준비되어있다. 각자 프로젝트 환경에 맞게 빌드를 선택하면 되며, 준비한 프로젝트를 사용하는 경우 Invoke top-level Maven targets을 누르고, Goals란에 test package를 입력하면 된다. 그리고 빌드 후 조치는 이후에 Slack과 연동해 알림을 해주는 방법에 대해 포스트할 계획이다.

그럼 이제 본격적으로 깃헙과 연결해보자. [Jenkins 관리] - [System 설정] 에 가면 Github 에 대한 설정이 있다. 이곳에 Github Server를 설정해야한다. 마찬가지로 Credentials을 위해 Add 버튼을 누르자.

Kind를 Secret text로 변경하고, Secret을 입력해야한다. 이 Secret은 Github에서 생성해야한다. Github 홈페이지로 가보자.

Github 설정 - Token 생성
[계정 설정(Personal Settings)] - [Developer settings] 으로 이동하자.

Personal access tokens 탭에서 token을 하나 생성해야한다. 즉, Jenkins 연결 시 인증을 위한 토큰이다. Generate new token 버튼을 누르자.

생성할 토큰에서 권한을 설정할 수 있다. 젠킨스가 필요한 권한인 repo와 admin:repo_hook을 체크하고 생성한다.

생성하면 화면에 보이는 암호화된 문자열이 Secret에 들어갈 키이다. 복사하여 Jenkins 로 돌아가서 Secret에 입력하여 Add한 후, Test Connection을 해보자.

테스트가 성공했다.

Github 설정 - Webhook생성
이제 인증을 위한 토큰을 생성해 Jenkins에서 인증까지 완료하였다. 이제 깃헙에서 특정 이벤트가 있을 때 hook을 할 수 있도록 webhook을 생성해보자.
젠킨스를 연동할 프로젝트로 돌아가 [Settings] - [Webhooks] 로 이동해 Add webhook을 눌러보자. Payload URL에는 요청을 보낼 URL 주소가 필요하다. 설치된 {젠킨스URL/github-webook/} 이 기본 설정이며 젠킨스에서 변경가능하다. 각자 URL을 입력한 후, Secret에는 이전에 발급받은 토큰을 입력한다. 그리고, 어떤 이벤트에 hook을 요청할 지 이벤트를 선택한다. 여기서는 push이벤트만 선택한다.

생성되면 바로 요청되어 요청을 받는지 테스트가 되며 옆에 체크표시가 나타난다.

연동 테스트
연동 테스트를 위해 push를 해보자.

Jenkins에 생성했던 프로젝트로 가보면 빌드가 하나 생성되어 있음을 확인할 수 있다. 또한, 콘솔 출력을 통해 빌드 로그 또한 확인할 수 있다.


master 브랜치에 있는 코드에는 Test 코드가 없다. Test 브랜치와 병합을 해 Push 해보자. 그러면 2개의 Test 까지 진행되는 것을 확인할 수 있을 것이다.
