Github ci/cd rsync to server from tag

By.

min read

My profile

Share this:

/.github/workflows/deploy.yml

AI written and manually improved:

name: Manual Deploy from Tag

on:
  workflow_dispatch:
    inputs:
      tag:
        description: 'Tag to deploy (e.g. 1.2.3)'
        required: true
        type: string

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - name: Log deployment request
        run: |
          echo "### Deployment Request" >> $GITHUB_STEP_SUMMARY
          echo "- **Triggered by:** ${{ github.actor }}" >> $GITHUB_STEP_SUMMARY
          echo "- **Tag requested:** ${{ inputs.tag }}" >> $GITHUB_STEP_SUMMARY
          echo "- **Timestamp:** $(date -u '+%Y-%m-%d %H:%M:%S UTC')" >> $GITHUB_STEP_SUMMARY
          echo "- **Run ID:** ${{ github.run_id }}" >> $GITHUB_STEP_SUMMARY
          echo "Deployment triggered by ${{ github.actor }} for tag ${{ inputs.tag }}"

      - name: Checkout repository (full history + tags)
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Validate tag exists
        run: |
          if ! git rev-parse "refs/tags/${{ inputs.tag }}" >/dev/null 2>&1; then
            echo "::error::Tag '${{ inputs.tag }}' does not exist in this repository."
            exit 1
          fi

      - name: Checkout specific tag
        run: git checkout "refs/tags/${{ inputs.tag }}"

      - name: Install SSH key
        uses: webfactory/ssh-agent@v0.9.0
        with:
          ssh-private-key: ${{ secrets.DEPLOY_SSH_KEY }}

      - name: Add server to known_hosts
        run: |
          mkdir -p ~/.ssh
          ssh-keyscan -H ${{ secrets.DEPLOY_HOST }} >> ~/.ssh/known_hosts

      - name: Debug SSH connection
        run: |
          ssh -vvv -o StrictHostKeyChecking=no ${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }} echo "connected"
          
      - name: Rsync to server
        run: |
          rsync -avz --delete --delete-excluded \
            --exclude='.git*' --exclude='*.md' \
            -e "ssh -o StrictHostKeyChecking=no" \
            ./ ${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}:${{ secrets.DEPLOY_PATH }}

      - name: Log deployment result
        if: always()
        run: |
          if [ "${{ job.status }}" == "success" ]; then
            echo "✅ Deployment of tag **${{ inputs.tag }}** by **${{ github.actor }}** succeeded." >> $GITHUB_STEP_SUMMARY
          else
            echo "❌ Deployment of tag **${{ inputs.tag }}** by **${{ github.actor }}** failed." >> $GITHUB_STEP_SUMMARY
          fi

Set settings -> actions -> secrets : DEPLOY_HOST, DEPLOY_PATH, DEPLOY_SSH_KEY, DEPLOY_USER and do your magic.

Share this:

Leave a Reply

Your email address will not be published. Required fields are marked *