Files
backend-springboot/.github/workflows/workflow.yml
2024-06-18 00:25:43 +08:00

68 lines
3.1 KiB
YAML

name: Deploy jar to EC2
on:
push:
branches: [ "main" ]
permissions:
id-token: write # This is required for requesting the JWT
contents: read # This is required for actions/checkout
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
cache: maven
- name: Create application-local.properties file
run: |
echo "spring.datasource.url=${{ secrets.DB_URL }}" >> src/main/resources/application-local.properties
echo "spring.datasource.username=${{ secrets.DB_USERNAME }}" >> src/main/resources/application-local.properties
echo "spring.datasource.password=${{ secrets.DB_PASSWORD }}" >> src/main/resources/application-local.properties
echo "spring.datasource.driver-class-name=${{ secrets.DB_DRIVER }}" >> src/main/resources/application-local.properties
echo "spring.jpa.hibernate.ddl-auto=update" >> src/main/resources/application-local.properties
echo "spring.jpa.show-sql=true" >> src/main/resources/application-local.properties
- name: Build with Maven
run: mvn -B package --file pom.xml
- name: Configure AWS Credentials
id: configure-aws-credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/${{ secrets.AWS_ROLE }}
aws-region: ${{ secrets.AWS_REGION }}
- name: Get Instance ID
id: get_instance_id
run: |
INSTANCE_ID=$(aws ec2 describe-instances --filters "Name=tag:Name,Values=safeqr-ec2" --query "Reservations[0].Instances[0].InstanceId" --output text)
echo "INSTANCE_ID=$INSTANCE_ID" >> $GITHUB_ENV
- name: Upload JAR to S3
run: |
aws s3 cp target/app-0.0.1-SNAPSHOT.jar s3://s3-bucket-safeqr/
- name: Get Presigned URL
id: presigned_url
run: |
URL=$(aws s3 presign s3://s3-bucket-safeqr/app-0.0.1-SNAPSHOT.jar --expires-in 3600)
echo "PRESIGNED_URL=$URL" >> $GITHUB_ENV
- name: Download and Verify JAR on EC2
run: |
aws ssm send-command --instance-ids ${{ env.INSTANCE_ID }} --document-name "AWS-RunShellScript" --comment "Download JAR file" --parameters 'commands=["curl -o /home/app-0.0.1-SNAPSHOT.jar ${{ env.PRESIGNED_URL }}", "ls -l /home/app-0.0.1-SNAPSHOT.jar"]'
- name: Create and Start Systemd Service
run: |
aws ssm send-command --instance-ids ${{ env.INSTANCE_ID }} --document-name "AWS-RunShellScript" --comment "Create and start service" --parameters 'commands=["echo \\"[Unit]\nDescription=Spring Boot Application\nAfter=network.target\n\n[Service]\nUser=ec2-user\nExecStart=/usr/bin/java -jar /home/app-0.0.1-SNAPSHOT.jar\nRestart=always\n\n[Install]\nWantedBy=multi-user.target\\" > /etc/systemd/system/springboot-app.service", "sudo systemctl daemon-reload", "sudo systemctl enable springboot-app", "sudo systemctl start springboot-app", "sudo systemctl status springboot-app"]'