-
Notifications
You must be signed in to change notification settings - Fork 0
63 lines (60 loc) · 2.35 KB
/
main.yaml
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
name: CI/CD
on: push
jobs:
build:
runs-on: ubuntu-latest
env:
ENV: dev
ECR_REPOSITORY: portfolio
SLACK_TOKEN: ${{ secrets.AWS_SECRET_KEY }}
steps:
- name: Checkout repo source
uses: actions/checkout@v4
- name: Login to Docker Hub
run: |
echo "${{ secrets.DOCKER_HUB_PASSWORD }}" | docker login --username ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Copy secret env
run: |
echo "SLACK_TOKEN=${{ secrets.SLACK_TOKEN }}" >> portfolio/environments/${ENV}.env
- name: Build, tag, and push
id: build-image
env:
ECR_REGISTRY: ${{ secrets.ECR_REGISTRY }}
RUNNER_ID: ${{ github.run_number }}
run: |
IMAGE_TAG=$RUNNER_ID
IMAGE_REPO_NAME=$ECR_REGISTRY/$ECR_REPOSITORY
LATEST_IMAGE=$IMAGE_REPO_NAME:latest
echo "Pulling latest image"
docker pull $LATEST_IMAGE || true
echo "Building images"
docker build --build-arg ENVIRONMENT=$ENV --cache-from $LATEST_IMAGE -t $IMAGE_REPO_NAME:latest -t $IMAGE_REPO_NAME:$IMAGE_TAG .
echo "Pushing images to ECR..."
docker push $IMAGE_REPO_NAME:latest
docker push $IMAGE_REPO_NAME:$IMAGE_TAG
echo "New image name=$IMAGE_REPO_NAME:$IMAGE_TAG"
deploy:
needs: [build]
runs-on: ubuntu-latest
env:
ECR_REPOSITORY: portfolio
ECR_REGISTRY: ${{ secrets.ECR_REGISTRY }}
RUNNER_ID: ${{ github.run_number }}
steps:
- name: Deploy
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USER }}
key: ${{ secrets.SSH_KEY }}
script: |
IMAGE_REPO_NAME=${{ env.ECR_REGISTRY }}/${{ env.ECR_REPOSITORY }}
IMAGE_TAG=${{ env.RUNNER_ID }}
awk -v old="$IMAGE_REPO_NAME:[0-9]+" -v new="$IMAGE_REPO_NAME:$IMAGE_TAG" '{gsub(old, new)}1' docker-compose.yaml > tmpfile && mv tmpfile docker-compose.yaml
docker pull $IMAGE_REPO_NAME:$IMAGE_TAG
docker-compose stop portfolio
docker-compose rm --force portfolio
docker-compose up -d --no-deps portfolio
echo "Deployed new image: $IMAGE_REPO_NAME:$IMAGE_TAG"
docker image prune --all --force
echo "Cleanup old images successfully"