Update GitHub Actions workflow with improved permissions and sudo com… #3
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 Dockerized Service | |
on: | |
push: | |
branches: [ main ] | |
pull_request: | |
branches: [ main ] | |
env: | |
REGISTRY: ghcr.io | |
IMAGE_NAME: ${{ github.repository }} | |
jobs: | |
build-and-deploy: | |
runs-on: ubuntu-latest | |
permissions: | |
contents: read | |
packages: write | |
steps: | |
- name: Checkout repository | |
uses: actions/checkout@v2 | |
- name: Set up Docker Buildx | |
uses: docker/setup-buildx-action@v2 | |
- name: Log in to the Container registry | |
uses: docker/login-action@v2 | |
with: | |
registry: ${{ env.REGISTRY }} | |
username: ${{ github.actor }} | |
password: ${{ secrets.GITHUB_TOKEN }} | |
- name: Extract metadata for Docker | |
id: meta | |
uses: docker/metadata-action@v4 | |
with: | |
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} | |
tags: | | |
type=sha,format=long | |
type=ref,event=branch | |
latest | |
- name: Build and push Docker image | |
uses: docker/build-push-action@v4 | |
with: | |
context: ./app | |
push: true | |
tags: ${{ steps.meta.outputs.tags }} | |
labels: ${{ steps.meta.outputs.labels }} | |
cache-from: type=gha | |
cache-to: type=gha,mode=max | |
- name: Create .env file content | |
run: | | |
echo "SECRET_MESSAGE='This is a secret message'" > .env | |
echo "USERNAME=admin" >> .env | |
echo "PASSWORD=secret123" >> .env | |
- name: Deploy to Target Node | |
uses: appleboy/ssh-action@master | |
with: | |
host: ${{ secrets.TARGET_HOST }} | |
username: ubuntu | |
key: ${{ secrets.SSH_PRIVATE_KEY }} | |
script: | | |
# Create required directories | |
sudo mkdir -p /opt/dockerized-service | |
sudo chown ubuntu:ubuntu /opt/dockerized-service | |
# Create .env file | |
cat > /opt/dockerized-service/.env << 'EOL' | |
SECRET_MESSAGE='This is a secret message' | |
USERNAME=admin | |
PASSWORD=secret123 | |
EOL | |
# Login to GitHub Container Registry | |
echo ${{ secrets.GITHUB_TOKEN }} | sudo docker login ghcr.io -u ${{ github.actor }} --password-stdin | |
# Pull the latest image | |
sudo docker pull ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest | |
# Stop and remove existing container if it exists | |
sudo docker stop dockerized-service || true | |
sudo docker rm dockerized-service || true | |
# Run the new container | |
sudo docker run -d \ | |
--name dockerized-service \ | |
--restart always \ | |
-p 3000:3000 \ | |
--env-file /opt/dockerized-service/.env \ | |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest | |
# Clean up old images | |
sudo docker image prune -f |