diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml new file mode 100644 index 0000000..1a5385d --- /dev/null +++ b/.github/workflows/gradle.yml @@ -0,0 +1,69 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. +# This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-gradle + +# Workflow 이름 +name: Spring Boot & Gradle CI/CD + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +permissions: + contents: read + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + # JDK 17 설치 + - name: Set up JDK 17 + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'temurin' + + # gradlew에 실행 권한을 부여합니다. + - name: Grant execute permisson for gradlew + run: chmod +x gradlew + + # test는 CI 과정에서 수행되므로 여기서는 `-x`로 테스트를 생략했습니다. + # `--stacktrace`로 더 자세한 로그가 출력되게 해줍니다. + - name: Build with Gradle (without Test) + run: ./gradlew clean build -x test --stacktrace + + # docker hub에 로그인하고 이미지를 빌드합니다. 이후에 push를 진행합니다. + # docker_username을 적지 않으면 push 시에 요청이 거부될 수 있습니다. + - name: Docker Hub build & push + run: | + docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} + docker build -t ${{ secrets.DOCKER_USERNAME }}/${{ secrets.DOCKER_REPO }} . + docker images + docker push ${{ secrets.DOCKER_USERNAME }}/${{ secrets.DOCKER_REPO }} + + # EC2에 접속하고 배포합니다. + - name: Deploy + uses: appleboy/ssh-action@master + with: + host: ${{ secrets.EC2_HOST }} + username: ${{ secrets.EC2_USERNAME }} + key: ${{ secrets.EC2_KEY }} + port: ${{ secrets.EC2_SSH_PORT }} + + script: | + sudo docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} + docker stop $(docker ps -a -q) + docker rm $(docker ps --filter 'status=exited' -a -q) + + sudo docker pull ${{ secrets.DOCKER_USERNAME }}/${{ secrets.DOCKER_REPO }} + sudo docker run -d -p 8080:8080 ${{ secrets.DOCKER_USERNAME }}/${{ secrets.DOCKER_REPO }}:latest +