외부 PC의 Jenkins에서 특정 서버에 원격(remote) 배포를 진행하는 과정을 정리하였다.
젠킨스를 통해 특정 서버에 SSH 통신로 접근하여 배포하는 과정이다. 배포 당하는 서버에는 Jenkins가 필요 없기에, 만일 배포되는 서버에 Jenkins가 설치되어 불필요한 자원을 사용하고 있다면 제거해주자.
젠킨스 삭제
경우에 따라 Java 설치해야할지도 모름
<aside> ➡️ **[**ec2-user ~]$ sudo dnf install java-17-amazon-corretto -y
</aside>
SSH Agent 플러그인 설치.
credentials 생성

경로 생성 및 권한 설정
다음과 같이 Jenkins-PipeLine에서 sshagent([”ssh_credentails_id”]) {}를 통해 등록된 크레덴셜을 사용하여 ssh 통신을 진행할 수 있다.
pipeline {
agent any
environment {
DEPLOY_SERVER = '127.0.0.1'
SSH_CREDENTIALS_ID = 'ssh-credentials-id'
}
tools {
gradle "gradle-test"
}
stages{
stage('Git Pull') {
steps {
git credentialsId: 'dori2005',
url: '<https://github.com/SWYP-LUCKY-SEVEN/back-end.git>',
branch: 'master'
}
}
stage('secret.yml download') {
steps {
withCredentials([file(credentialsId: 'showtudy_secret', variable: 'secretConfigFile')]) {
script {
sh 'sudo cp $secretConfigFile /var/lib/jenkins/workspace/showtudy/src/main/resources/application-secret.properties'
}
}
}
}
stage('Build') {
steps {
sh "gradle clean build"
}
}
stage('Kill Process on Remote Server') {
steps {
sshagent([env.SSH_CREDENTIALS_ID]) {
sh '''
if ssh ec2-user@${DEPLOY_SERVER} 'sudo lsof -t -i:8080'; then
echo "> Kill port 8080"
ssh ec2-user@${DEPLOY_SERVER} 'sudo lsof -t -i:8080 | xargs sudo kill -9'
ssh ec2-user@${DEPLOY_SERVER} 'while sudo lsof -t -i:8080; do sleep 1; done'
fi
'''
}
}
}
stage('Deploy to Remote Server') {
steps {
sshagent([env.SSH_CREDENTIALS_ID]) {
sh '''
scp -o StrictHostKeyChecking=no /var/lib/jenkins/workspace/showtudy/build/libs/swip-0.0.1-SNAPSHOT.jar ec2-user@${DEPLOY_SERVER}:/opt/{path}/
ssh ec2-user@${DEPLOY_SERVER} 'sudo nohup java -jar /opt/{path}/swip-0.0.1-SNAPSHOT.jar > /opt/{path}/nohup.out 2>&1 &'
'''
}
}
}
}
}
로그 만들기
nohup 사용법과 nohup.out 파일 명 변경, 로그 없이, 날짜 별로 rotation 하는 방법 ( Linux )
웹 훅 구분하기
<aside> ➡️ http://<JENKINS_URL>/github-webhook/?project=A http://<JENKINS_URL>/github-webhook/?project=B
</aside>