don't stop believing

[macaron 2] 빌드와 배포 환경 만들기 (Gitlab, Jenkins, ssh) 본문

Swift/Perfect

[macaron 2] 빌드와 배포 환경 만들기 (Gitlab, Jenkins, ssh)

Tongchun 2018. 1. 8. 15:04

개발에서 부터 배포까지의 시스템을 만들고 싶었습니다.

우선 이게 최선인지는 좀 더 살펴보기로 하고 지금까지 진행한 걸 정리해 봅니다.


환경 설명입니다.

  • 개발 PC: Mac
  • Gitlab: (소스 관리) Ubuntu 16.04.3 / Gitlab 9.5.2
  • Jenkins: (CI 서버) Ubuntu 16.04.3 / Jenkins 2.89.2
  • Macaron 서버: 사내 서비스용 서버 (Ubuntu 16.04.3)

먼저 Gitlab에 project를 만들고 관리합니다.


개발 PC에서 개발이 완료되면 Gitlab에 push 합니다.

매번하는 push라 sh 파일을 만들어 줍니다. (pushGit.sh)

#!/bin/sh
# push gitlab

if [ "$1" = "" ]
then
	echo "You need to write a push comment."
else
	git add --all
	git commit -m "$1"
	git push -u origin master
fi

개발 PC에서 compile 후 테스트에 문제가 없다면 gitlab에 push 합니다.

sh pushGit.sh "commit messages"


Gitlab에 push event가 발생하면 Jenkins에서 빌드를 합니다.

[Gitlab에 연결해 빌드하기]


Jenkins에서 빌드가 정상적으로 실행되었다면 Macaron 서버의 startMacaonAPI.sh를 실행합니다.

Macaron 서버에 배포하는 것은 좀 더 찾아봐야 겠지만 우선은 Macaron 서버에서 gitlab의 macaron-api 프로젝트를 clone해서 release 빌드를 하게 됩니다.

#!/bin/sh

macaronPath=/home/macaron/macaron-api

if [ -d "$macaronPath" ]
then
	echo "Directory exists : $macaronPath"
	pkill macaron-api
	rm -rf $macaronPath
fi

git clone http://gitlab.ngle.co.kr/tongchun/macaron-api.git
cd $macaronPath

swift package update
swift build -c release 
nohup .build/release/macaron-api >> nohup.out 2>&1 &

** nohup search **

nohup 을 사용했을때 prompt로 돌아오지 않는 경우가 있습니다. 처음 startMacaronAPI.sh를 작성할때 마지막 line에 .build/release/macaron-api & 이렇게만 사용했는데 jenkins에서 실행시 마지막 line에서 return 되는게 없어 무한 로딩되게 됩니다. 실행은 정상이었죠. nohup을 사용할 때 prompt로 돌아오기 위해서는 nohup <command> >> nohup.out 2>&! & 이렇게 해주면 됩니다.


sh 파일 이름은 startMacaronAPI.sh로 했습니다. 이걸 Jenkins 에서 ssh로 호출해 줍니다.

Jenkins 서버와 Macaron 서버는 ssh key를 등록해 비번 입력 없이 ssh 연결이 가능하도록 했습니다.

[ssh 패스워드 없이 자동 로그인]

(! jenkins 계정으로 key를 생성하고 등록해야 합니다.)


Jenkins에서 Macaron 서버의 startMacaronAPI.sh를 호출하려면 아래처럼 명령합니다.

$ ssh macaron@192.168.1.12 "bash --login -c 'sh ~/startMacaronAPI.sh'"

ssh를 이용해 remote server에 command를 실행할때 명령이 재대로 먹지 않지 않을 수 있습니다. 찾아보니 login shell과 interactive shell이 다르다고 합니다.

https://stackoverflow.com/questions/216202/why-does-an-ssh-remote-command-get-fewer-environment-variables-then-when-run-man

그래서 interactive shell을 사용하려면 source /etc/profile;을 먼저 실행하고 뒤에 명령을 실행합니다.


위 명령을 Jenkins에 등록합니다. (빌드 후 조치로 하고 싶은데 shell script만 실행하는게 없네요.)

Build에서 Add build step 버튼을 눌러 Execute shell을 추가합니다.

이제 개발PC에서 build에 문제가 없다면 pushGit.sh로 Gitlab에 push하고, Gitlab은 push event를 jenkins에 보내고, Jenkins는 Build가 끝나면 Macaron 서버의 startMacaronAPI.sh를 호출해 api 서버를 띄우게 됩니다.


Comments