Github Actions CI/CD

Sungju Kim·2024년 10월 20일

Sparta_Coding_Camp_TIL

목록 보기
51/53

Following is the Github Actions Scripts use for CI/CD.

name: Build and Deploy to EC2

# the following script is only triggered when there is a push to the remote branch
on:
  push:
    branches:
      - main

# permit workflow to read the repo
permissions:
  contents: read
  

# defining the jobs for the workflow
jobs:

  # defines the running environment to the latest version of ubuntu
  build:
    runs-on: ubuntu-latest
    
    # checks out (or clones) the repository's code into the workflow environment 
    # so that subsequent steps in the workflow can access and work with the code.
    steps:
    - uses: actions/checkout@v3
     
    # temurin = JDK provided by Adoptium
    - name: Set up JDK 17
      uses: actions/setup-java@v3
      with:
        java-version: '17'
        distribution: 'temurin'

    # gradle wrapper = allows gradle build w/o downloading gradle        
    - name: Grant execute permission for gradlew
      run: chmod +x gradlew

    - name: Build with Gradle Wrapper
      run: ./gradlew build

    # upload the .jar file on github as an artifact
    - name: Upload build artifact
      uses: actions/upload-artifact@v4
      with:
        name: trelloServer
        path: build/libs/spring-trello-0.0.1-SNAPSHOT.jar

  deploy:
    needs: build
    runs-on: ubuntu-latest

    # Download the artifact (.jar file)
    steps:
    - name: Download build artifact
      uses: actions/download-artifact@v4
      with:
        name: trelloServer
        path: build/libs/

    # Save the EC2 SSH key as a `private_key.pem` file (location is on the GitHub server).
	# Use SCP to copy the JAR file to the EC2 server.
	# Use SSH to connect to the EC2 server, stop the currently running Java process, then create and run a new Java process!
    	# If NLP is applied, modify the IP to a domain.
    	# If more EC2 instances are added, include additional `run` commands.
    - name: Deploy to EC2
      run: |
        echo "${{ secrets.EC2_SSH_KEY }}" > private_key.pem
        chmod 600 private_key.pem
        scp -i private_key.pem -o StrictHostKeyChecking=no build/libs/spring-trello-0.0.1-SNAPSHOT.jar ${{ secrets.EC2_USERNAME }}@${{ secrets.EC2_HOST }}:/home/${{ secrets.EC2_USERNAME }}/trelloServer.jar
        ssh -i private_key.pem -o StrictHostKeyChecking=no ${{ secrets.EC2_USERNAME }}@${{ secrets.EC2_HOST }} "pgrep java | xargs kill -9; nohup java -jar /home/${{ secrets.EC2_USERNAME }}/trelloServer.jar > app.log 2>&1 &"
        rm -f private_key.pem
profile
Fully ✨committed✨ developer, always eager to learn!

0개의 댓글