Deploy to EC2 #43
This file contains hidden or 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 EC2 | |
| on: | |
| workflow_dispatch: | |
| jobs: | |
| deploy: | |
| runs-on: ubuntu-latest | |
| steps: | |
| - name: Checkout the branch | |
| uses: actions/checkout@v4 | |
| with: | |
| ref: ${{ github.ref_name }} | |
| - name: Configure AWS Credentials | |
| uses: aws-actions/configure-aws-credentials@v4 | |
| with: | |
| aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} | |
| aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} | |
| aws-region: ${{ secrets.AWS_REGION }} | |
| - name: Login to Amazon ECR | |
| id: ecr-login | |
| run: | | |
| aws ecr get-login-password --region ${{ secrets.AWS_REGION }} | \ | |
| docker login --username AWS --password-stdin ${{ secrets.ECR_REGISTRY }} | |
| - name: Build & Push aicacia-api | |
| run: | | |
| docker buildx build \ | |
| --output type=registry \ | |
| --push \ | |
| --platform linux/amd64 \ | |
| --tag ${{ secrets.ECR_REGISTRY }}/aicacia-api:latest \ | |
| ./api | |
| - name: Build & Push aicacia-webapp | |
| run: | | |
| docker buildx build \ | |
| --output type=registry \ | |
| --push \ | |
| --platform linux/amd64 \ | |
| --tag ${{ secrets.ECR_REGISTRY }}/aicacia-webapp:latest \ | |
| ./webapp | |
| - name: Delete untagged images | |
| run: | | |
| REPOSITORIES=("aicacia-api" "aicacia-webapp") | |
| for repo in "${REPOSITORIES[@]}"; do | |
| echo "Getting untagged image digests for $repo..." | |
| DIGESTS=$(aws ecr list-images \ | |
| --repository-name $repo \ | |
| --filter "tagStatus=UNTAGGED" \ | |
| --query 'imageIds[*].imageDigest' \ | |
| --output text \ | |
| --region ${{ secrets.AWS_REGION }}) | |
| if [ -z "$DIGESTS" ]; then | |
| echo "No untagged images found in $repo." | |
| else | |
| echo "Deleting untagged images from $repo..." | |
| for digest in $DIGESTS; do | |
| aws ecr batch-delete-image \ | |
| --repository-name $repo \ | |
| --image-ids imageDigest=$digest \ | |
| --region ${{ secrets.AWS_REGION }} | |
| done | |
| fi | |
| done | |
| - name: Upload docker-compose.yml and deploy.sh to EC2 | |
| uses: appleboy/scp-action@v0.1.7 | |
| with: | |
| host: ${{ secrets.EC2_PUBLIC_IP }} | |
| username: ec2-user | |
| key: ${{ secrets.EC2_SSH_PRIVATE_KEY }} | |
| source: "infra/deploy.sh,docker-compose.yml" | |
| target: "/home/ec2-user" | |
| - name: Run deployment script on EC2 | |
| uses: appleboy/ssh-action@v1.2.2 | |
| with: | |
| host: ${{ secrets.EC2_PUBLIC_IP }} | |
| username: ec2-user | |
| key: ${{ secrets.EC2_SSH_PRIVATE_KEY }} | |
| script: | | |
| chmod +x /home/ec2-user/infra/deploy.sh | |
| /home/ec2-user/infra/deploy.sh |