Last active
July 13, 2024 17:52
-
-
Save HarshaSuranjith/0d6468c1fca19c732a1c6cb6756ac84a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pipeline { | |
agent any | |
environment { | |
SSH_CREDENTIALS = 'your-ssh-credentials-id' // The ID of the SSH credentials in Jenkins | |
REMOTE_USER = 'your-remote-user' // The user on the remote server | |
REMOTE_HOST = 'your-remote-host' // The IP or hostname of the remote server | |
REMOTE_DIR = '/path/to/your/app' // The directory on the remote server where the app will be deployed | |
} | |
stages { | |
stage('Check Build Dependencies') { | |
steps { | |
script { | |
// Check if Node.js is installed locally | |
def nodeInstalled = sh(script: 'command -v node', returnStatus: true) == 0 | |
if (!nodeInstalled) { | |
error("Node.js is not installed on the Jenkins build agent.") | |
} | |
// Check if npm is installed locally | |
def npmInstalled = sh(script: 'command -v npm', returnStatus: true) == 0 | |
if (!npmInstalled) { | |
error("npm is not installed on the Jenkins build agent.") | |
} | |
} | |
} | |
} | |
stage('Clone Repository') { | |
steps { | |
git 'https://github.com/username/repository.git' | |
} | |
} | |
stage('Install Dependencies') { | |
steps { | |
sh 'npm install' | |
} | |
} | |
stage('Test') { | |
steps { | |
sh 'npm test' | |
} | |
} | |
stage('Build') { | |
steps { | |
sh 'npm run build' | |
} | |
} | |
stage('Check Remote Dependencies') { | |
steps { | |
sshagent(credentials: [SSH_CREDENTIALS]) { | |
sh """ | |
ssh ${REMOTE_USER}@${REMOTE_HOST} << EOF | |
if ! command -v node &> /dev/null; then | |
echo "Node.js is not installed on the remote server. Please install Node.js." | |
exit 1 | |
fi | |
if ! command -v npm &> /dev/null; then | |
echo "npm is not installed on the remote server. Please install npm." | |
exit 1 | |
fi | |
if ! command -v pm2 &> /dev/null; then | |
echo "PM2 is not installed on the remote server. Installing PM2..." | |
npm install -g pm2 | |
fi | |
EOF | |
""" | |
} | |
} | |
} | |
stage('Deploy') { | |
steps { | |
sshagent(credentials: [SSH_CREDENTIALS]) { | |
sh """ | |
scp -r * ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DIR} | |
ssh ${REMOTE_USER}@${REMOTE_HOST} << EOF | |
cd ${REMOTE_DIR} | |
npm install --production | |
pm2 restart all || pm2 start app.js --name "my-app" | |
EOF | |
""" | |
} | |
} | |
} | |
} | |
post { | |
success { | |
echo 'Deployment successful!' | |
} | |
failure { | |
echo 'Deployment failed.' | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment