Make SSH operations non-interactive via script #6
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: Docker Build Deploy | |
on: | |
push: | |
branches: | |
- main | |
env: | |
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} | |
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} | |
DOCKER_IMAGE_NAME: ${{secrets.DOCKER_IMAGE_NAME}} | |
SSH_USERNAME: ${{ secrets.SSH_USERNAME }} | |
SSH_HOST: ${{ secrets.SSH_HOST }} | |
jobs: | |
create-docker-image: | |
runs-on: ubuntu-latest | |
steps: | |
- name: Checkout code | |
uses: actions/checkout@v2 | |
- name: Set up Docker Buildx | |
uses: docker/setup-buildx-action@v2 | |
- name: Log in to Docker Hub | |
uses: docker/login-action@v2 | |
with: | |
username: ${{ secrets.DOCKER_USERNAME }} | |
password: ${{ secrets.DOCKER_PASSWORD }} | |
- name: Build Docker image | |
run: | | |
cd server | |
docker build -f Dockerfile -t ${{secrets.DOCKER_USERNAME}}/${{secrets.DOCKER_IMAGE_NAME}}:latest . | |
- name: Push Docker image | |
run: docker push ${{secrets.DOCKER_USERNAME}}/${{secrets.DOCKER_IMAGE_NAME}}:latest | |
deployment: | |
needs: create-docker-image | |
runs-on: ubuntu-latest | |
steps: | |
- name: Install SSH client | |
run: sudo apt-get install -y openssh-client | |
- name: Create deployment script | |
run: | | |
cat << 'EOF' > deploy.sh | |
#!/bin/bash | |
set -e | |
echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin | |
docker pull ${{ secrets.DOCKER_USERNAME }}/${{secrets.DOCKER_IMAGE_NAME}}:latest | |
# Navigate to your project directory | |
cd /home/ubuntu/projects/servdomain | |
sed -i 's|image: .*$|image: ${{ secrets.DOCKER_USERNAME }}/${{secrets.DOCKER_IMAGE_NAME}}|' docker-compose.yml | |
# Restart the Docker containers using Docker Compose | |
docker-compose down | |
docker-compose up -d | |
# Clean up | |
docker system prune -af | |
EOF | |
- name: Make deployment script executable | |
run: chmod +x deploy.sh | |
- name: Deploy to EC2 | |
env: | |
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} | |
DOCKER_IMAGE_NAME: ${{secrets.DOCKER_IMAGE_NAME}} | |
run: | | |
echo "${{ secrets.EC2_SSH_KEY }}" > ec2-key.pem | |
chmod 600 ec2-key.pem | |
scp -i ec2-key.pem -o StrictHostKeyChecking=no deploy.sh ${{ secrets.SSH_USERNAME }}@${{ secrets.SSH_HOST }}:/home/${{ secrets.SSH_USERNAME }}/deploy.sh | |
ssh -o StrictHostKeyChecking=no -i ec2-key.pem ${{ secrets.SSH_USERNAME }}@${{ secrets.SSH_HOST }} /home/${{ secrets.SSH_USERNAME }}/deploy.sh | |
- name: Clean up | |
run: rm -f ec2-key.pem deploy.sh |