Repository navigation
86 lines (72 loc) · 2.88 KB
/
Copy pathci-cd.yml
File metadata and controls
86 lines (72 loc) · 2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
name: CI/CD Pipeline
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: '17'
distribution: 'temurin'
cache: maven
- name: Generate test RSA keys
run: |
mkdir -p src/test/resources/keys
openssl genrsa -out src/test/resources/keys/private.pem 2048
openssl rsa -in src/test/resources/keys/private.pem -pubout -out src/test/resources/keys/public.pem
- name: Run tests
run: ./mvnw test
env:
SPRING_PROFILES_ACTIVE: local
- name: Build with Maven
run: ./mvnw clean package -DskipTests
- name: Build and push Docker image
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
run: |
IMAGE_NAME_LOWER=$(echo ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} | tr '[:upper:]' '[:lower:]')
echo "${{ secrets.GITHUB_TOKEN }}" | docker login ${{ env.REGISTRY }} -u ${{ github.actor }} --password-stdin
docker build -t ${IMAGE_NAME_LOWER}:${{ github.sha }} .
docker push ${IMAGE_NAME_LOWER}:${{ github.sha }}
docker tag ${IMAGE_NAME_LOWER}:${{ github.sha }} ${IMAGE_NAME_LOWER}:latest
docker push ${IMAGE_NAME_LOWER}:latest
deploy:
needs: build-and-test
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- name: Deploy to EC2
uses: appleboy/ssh-action@v1.1.0
with:
host: ${{ secrets.EC2_HOST }}
username: ${{ secrets.EC2_USERNAME }}
key: ${{ secrets.EC2_SSH_KEY }}
script: |
cd ~/auth-microservice
# Log in to GHCR
echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u ${{ github.actor }} --password-stdin
# Create secure .env file for production
cat > .env.prod << EOF
GITHUB_REPOSITORY=$(echo ${{ github.repository }} | tr '[:upper:]' '[:lower:]')
DB_USERNAME=${{ secrets.DB_USERNAME }}
DB_PASSWORD=${{ secrets.DB_PASSWORD }}
SPRING_PROFILES_ACTIVE=prod
EOF
# Pull latest images and deploy with production profile
docker-compose --env-file .env.prod pull
docker-compose --env-file .env.prod down
docker-compose --env-file .env.prod up -d
# Clean up sensitive file
rm -f .env.prod
# Verify deployment
sleep 30
curl -f http://localhost:8080/actuator/health || exit 1
echo "Deployment successful"