1+ # This workflow builds the Spring Boot application and deploys it to VM.
2+ # It is triggered on pushes to the 'main' branch or can be run manually.
3+
4+ name : Build and Deploy to VM
5+
6+ on :
7+ push :
8+ branches :
9+ - main
10+
11+ # Allows us to run this workflow manually from the Actions tab
12+ workflow_dispatch :
13+
14+ jobs :
15+ build :
16+ name : Build JAR
17+ runs-on : ubuntu-latest
18+
19+ steps :
20+ - name : Checkout Code
21+ uses : actions/checkout@v4
22+
23+ - name : Set up JDK 17
24+ uses : actions/setup-java@v4
25+ with :
26+ java-version : ' 17'
27+ distribution : ' temurin' # A popular, high-quality build of OpenJDK
28+
29+ - name : Cache Maven packages
30+ uses : actions/cache@v4
31+ with :
32+ path : ~/.m2/repository
33+ key : ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
34+ restore-keys : |
35+ ${{ runner.os }}-maven-
36+
37+ - name : Build with Maven Wrapper
38+ run : |
39+ chmod +x mvnw
40+ ./mvnw clean package
41+
42+ - name : Upload JAR artifact
43+ uses : actions/upload-artifact@v4
44+ with :
45+ name : app-jar
46+ path : target/leetcode-api-*.jar
47+ retention-days : 1 # We only need this artifact for the next job
48+
49+ deploy :
50+ name : Deploy to VM
51+ runs-on : ubuntu-latest
52+ needs : build # This job will only run if the 'build' job succeeds
53+
54+ steps :
55+ - name : Download JAR artifact
56+ # Download the 'app-jar' artifact that the 'build' job uploaded
57+ uses : actions/download-artifact@v4
58+ with :
59+ name : app-jar
60+ path : . # Download to the current directory
61+
62+ - name : Find JAR file name
63+ # The downloaded file has a version number. We need to find the
64+ # exact file name to use it in the next step.
65+ id : find_jar
66+ run : echo "JAR_NAME=$(ls leetcode-api-*.jar)" >> $GITHUB_OUTPUT
67+
68+ - name : Copy JAR to VM via SCP
69+
70+ uses : appleboy/scp-action@v1.0.3
71+ with :
72+ host : ${{ secrets.VM_HOST }}
73+ username : ${{ secrets.VM_USERNAME }}
74+ key : ${{ secrets.VM_SSH_KEY }}
75+ port : 22
76+ source : ${{ steps.find_jar.outputs.JAR_NAME }}
77+ target : " /opt/leetstats-api" # This is the WorkingDirectory from our systemd file
78+ rename : " app.jar"
79+
80+ - name : SSH and Restart Service
81+ # This action securely logs into our VM and runs the restart commands
82+ uses : appleboy/ssh-action@v1.0.3a
83+ with :
84+ host : ${{ secrets.VM_HOST }}
85+ username : ${{ secrets.VM_USERNAME }}
86+ key : ${{ secrets.VM_SSH_KEY }}
87+ port : 22
88+ script : |
89+ echo "Stopping leetstats-api service..."
90+ sudo systemctl stop leetstats-api
91+
92+ echo "Starting leetstats-api service with new JAR..."
93+ sudo systemctl start leetstats-api
94+
95+ echo "Checking service status..."
96+ sleep 5 # Give the service a moment to start
97+ sudo systemctl status leetstats-api
98+ echo "Deployment complete."
0 commit comments