Update main.yml #17
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
name: Deploy to Cloud Run using Docker | |
on: | |
push: | |
branches: | |
- main # Adjust to your branch | |
env: | |
SERVICE_NAME: ${{ secrets.CLOUD_RUN_SERVICE }} | |
REGION: ${{ secrets.REGION }} | |
PROJECT_ID: ${{ secrets.GCP_PROJECT_ID }} | |
jobs: | |
deploy: | |
runs-on: ubuntu-latest | |
steps: | |
- name: Checkout code | |
uses: actions/checkout@v3 | |
- name: Authenticate with Google Cloud | |
uses: google-github-actions/auth@v1 | |
with: | |
project_id: ${{ env.PROJECT_ID }} | |
credentials_json: ${{secrets.GCP_SERVICE_ACCOUNT_KEY}} | |
- name: Set Google Cloud Project | |
run: gcloud config set project ${{ env.PROJECT_ID }} | |
- name: Configure Docker authentication with GCR | |
run: gcloud auth configure-docker | |
- name: Build Docker image | |
run: | | |
export IMAGE_NAME=gcr.io/${{ env.PROJECT_ID }}/${{env.SERVICE_NAME}}:${{ github.sha }} | |
docker build --platform linux/amd64 -t $IMAGE_NAME . | |
- name: Push Docker image to GCR | |
run: | | |
export IMAGE_NAME=gcr.io/${{ env.PROJECT_ID }}/${{env.SERVICE_NAME}}:${{ github.sha }} | |
docker push $IMAGE_NAME | |
- name: Fetch application.properties from Secret Manager | |
run: | | |
gcloud secrets versions access latest --secret="magnus-staging-properties" --project=${{ env.PROJECT_ID }} > ${{github.workspace}}/application.properties | |
cat ${{github.workspace}}/application.properties | |
- name: Deploy to Cloud Run | |
run: | | |
gcloud run deploy $SERVICE_NAME \ | |
--image gcr.io/${{ env.PROJECT_ID }}/${{env.SERVICE_NAME}}:${{ github.sha }} \ | |
--region ${{env.REGION}} \ | |
--platform managed \ | |
--allow-unauthenticated \ | |
--no-traffic | |
--set-env-vars SPRING_CONFIG_LOCATION="file:/${{github.workspace}}/application.properties" \ | |
--timeout=600s # Extend to 10 minutes if needed | |
- name: Shift traffic to new revision | |
run: | | |
gcloud run services update-traffic ${{ env.SERVICE_NAME }} \ | |
--to-latest \ | |
--region="${{ env.REGION }}" | |
- name: Delete old revisions | |
run: | | |
revisions=$(gcloud run revisions list --service ${{env.SERVICE_NAME}} --format="value(NAME)" --sort-by="~CREATE_TIME") | |
echo "Revisions: $revisions" | |
to_delete=$(echo "$revisions" | sed -n '3,$p') # Keep only the latest 2 | |
if [ -n "$to_delete" ]; then | |
echo "$to_delete" | xargs -I {} gcloud run revisions delete {} --quiet | |
fi |