当前位置:首页 > 数字漫游 > 正文内容

GitHub Actions 让您轻松实现所有软件工作流程的自动化 CI/CD 功能。 实例代码

reik221个月前 (11-12)数字漫游609
name: Deploy Telegram Bot to VPS

on:
  push:
    branches:
      - main
  workflow_dispatch:

jobs:
  deploy:
    name: Deploy to VPS
    runs-on: ubuntu-latest
   
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
     
      - name: Setup Go environment
        uses: actions/setup-go@v4
        with:
          go-version: '1.21'
     
      - name: Download dependencies
        run: |
          echo "Downloading Go modules..."
          go mod tidy
          go mod download
          echo "Dependencies downloaded successfully"
     
      - name: Build and test locally
        run: |
          echo "Building application..."
          go build -o bot
          echo "Build completed successfully"
          ls -lh bot
     
      - name: Configure SSH key
        env:
          VPS_HOST: ${{ secrets.VPS_HOST }}
          VPS_PORT: ${{ secrets.VPS_PORT }}
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          ssh-keyscan -p ${VPS_PORT} -H ${VPS_HOST} >> ~/.ssh/known_hosts 2>/dev/null || true
          # Configure SSH to skip host key verification on first run
          echo "Host ${VPS_HOST}" >> ~/.ssh/config
          echo "  StrictHostKeyChecking accept-new" >> ~/.ssh/config
          echo "  Port ${VPS_PORT}" >> ~/.ssh/config
          chmod 600 ~/.ssh/config
          echo "SSH key configured"
     
      - name: Deploy to VPS
        env:
          VPS_HOST: ${{ secrets.VPS_HOST }}
          VPS_USER: ${{ secrets.VPS_USER }}
          VPS_PORT: ${{ secrets.VPS_PORT }}
          VPS_APP_PATH: ${{ secrets.VPS_APP_PATH }}
        run: |
          # Create deploy script
          cat > /tmp/deploy.sh << 'DEPLOY_EOF'
          #!/bin/bash
          set -e
         
          echo "=========================================="
          echo "Starting GitHub Actions"
          echo "=========================================="
         
          # Use environment variables directly instead of positional parameters
          VPS_USER_NAME="${VPS_USER}"
          VPS_APP_PATH_VAR="${VPS_APP_PATH}"
         
          if [ -z "$VPS_USER_NAME" ] || [ -z "$VPS_APP_PATH_VAR" ]; then
            echo "Error: VPS_USER or VPS_APP_PATH environment variable not set"
            exit 1
          fi
         
          echo "Deploying as user: $VPS_USER_NAME"
          echo "Deploy path: $VPS_APP_PATH_VAR"
         
          # Navigate to parent directory and ensure repo exists
          PARENT_DIR=$(dirname "${VPS_APP_PATH_VAR}")
          REPO_NAME=$(basename "${VPS_APP_PATH_VAR}")
          mkdir -p "${PARENT_DIR}"
          cd "${PARENT_DIR}"
         
          # If directory doesn't exist, clone it with the correct user
          if [ ! -d "${VPS_APP_PATH_VAR}" ]; then
            echo "Directory does not exist, cloning repository..."
            # Use sudo with password from stdin (user has password set in VPS init script)
            echo "xiewei123" | sudo -S -u "${VPS_USER_NAME}" git clone https://github.com/reikwei/telegram-bot-vps-install.git "${REPO_NAME}"
          fi
         
          cd "${VPS_APP_PATH_VAR}"
          echo "Current directory: $(pwd)"
         
          # Configure git safe directory for the user
          echo "xiewei123" | sudo -S -u "${VPS_USER_NAME}" git config --global --add safe.directory "${VPS_APP_PATH_VAR}"
         
          # Ensure we have the remote configured
          if ! echo "xiewei123" | sudo -S -u "${VPS_USER_NAME}" git remote | grep -q origin; then
            echo "Adding git remote..."
            echo "xiewei123" | sudo -S -u "${VPS_USER_NAME}" git remote add origin https://github.com/reikwei/telegram-bot-vps-install.git
          fi
         
          # Fetch and pull latest code with correct user
          echo "Fetching latest code from main branch..."
          echo "xiewei123" | sudo -S -u "${VPS_USER_NAME}" git fetch origin main
          echo "xiewei123" | sudo -S -u "${VPS_USER_NAME}" git reset --hard origin/main
          echo "Code updated successfully"
         
          echo "Building bot application..."
          # Create bin directory
          mkdir -p "${VPS_APP_PATH_VAR}/bin"
          # Change ownership - need to use sudo with password
          echo "xiewei123" | sudo -S chown -R "${VPS_USER_NAME}:${VPS_USER_NAME}" "${VPS_APP_PATH_VAR}"
         
          # Build the application with proper environment
          # Source the user's profile to ensure Go environment variables are set
          echo "xiewei123" | sudo -S -u "${VPS_USER_NAME}" bash -c "
            source ~/.bashrc 2>/dev/null || true
            cd '${VPS_APP_PATH_VAR}'
            echo 'Go path check:'
            which go || echo 'Go not in PATH, trying /usr/local/go/bin/go'
            /usr/local/go/bin/go version
            export PATH=/usr/local/go/bin:\$PATH
            export GOPATH=\$HOME/go
            export PATH=\$PATH:\$GOPATH/bin
            go mod download && go build -o bin/tg-bot
          "
         
          if [ $? -ne 0 ]; then
            echo "Build failed!"
            exit 1
          fi
         
          # Verify the binary was created
          if [ ! -f "${VPS_APP_PATH_VAR}/bin/tg-bot" ]; then
            echo "Binary file not found after build!"
            exit 1
          fi
         
          echo "Build completed successfully"
          ls -lh "${VPS_APP_PATH_VAR}/bin/tg-bot"
         
          echo "Stopping bot service..."
          sudo -n systemctl stop tg-bot.service 2>/dev/null || echo "Service was not running"
          sleep 2
         
          echo "Starting bot service..."
          sudo -n systemctl start tg-bot.service
         
          sleep 3
          if sudo -n systemctl is-active --quiet tg-bot.service; then
            echo "Bot service started successfully"
            sudo -n systemctl status tg-bot.service --no-pager
          else
            echo "Bot service failed to start!"
            echo ""
            echo "Service status:"
            sudo -n systemctl status tg-bot.service --no-pager || true
            echo ""
            echo "Recent logs:"
            sudo -n journalctl -u tg-bot.service -n 30 --no-pager
            exit 1
          fi
         
          echo "=========================================="
          echo "Deployment completed successfully"
          echo "=========================================="
          DEPLOY_EOF
         
          # Ensure the script was created
          if [ ! -f /tmp/deploy.sh ]; then
            echo "ERROR: Failed to create deploy script"
            exit 1
          fi
         
          chmod +x /tmp/deploy.sh
         
          # Verify the deploy script exists and is readable
          echo "Deploy script created successfully:"
          ls -lh /tmp/deploy.sh
          file /tmp/deploy.sh
          wc -l /tmp/deploy.sh
         
          # Copy deploy script to VPS
          echo ""
          echo "Copying deploy script to VPS..."
          echo "VPS details - Host: ${VPS_HOST}, User: ${VPS_USER}, Port: ${VPS_PORT}"
         
          scp -i ~/.ssh/deploy_key -P ${VPS_PORT} /tmp/deploy.sh "${VPS_USER}@${VPS_HOST}:/tmp/deploy.sh" || {
            echo "ERROR: Failed to copy deploy script to VPS"
            echo "Trying alternative method..."
            ssh -i ~/.ssh/deploy_key -p ${VPS_PORT} "${VPS_USER}@${VPS_HOST}" "cat > /tmp/deploy.sh" < /tmp/deploy.sh
            if [ $? -ne 0 ]; then
              exit 1
            fi
          }
         
          echo "Deploy script copied successfully"
         
          # Execute deploy script on VPS with environment variables
          echo ""
          echo "Executing deploy script on VPS..."
          ssh -i ~/.ssh/deploy_key -p ${VPS_PORT} "${VPS_USER}@${VPS_HOST}" "export VPS_USER=${VPS_USER}; export VPS_APP_PATH=${VPS_APP_PATH}; bash /tmp/deploy.sh"
     
      - name: Check service status
        if: success()
        env:
          VPS_HOST: ${{ secrets.VPS_HOST }}
          VPS_USER: ${{ secrets.VPS_USER }}
          VPS_PORT: ${{ secrets.VPS_PORT }}
        run: |
          ssh -i ~/.ssh/deploy_key -p ${VPS_PORT} "${VPS_USER}@${VPS_HOST}" << 'STATUS_EOF'
         
          echo "=========================================="
          echo "Checking bot service status"
          echo "=========================================="
          sudo systemctl status tg-bot.service --no-pager
          echo ""
          echo "Recent service logs:"
          sudo journalctl -u tg-bot.service -n 10 --no-pager
         
          STATUS_EOF
     
      - name: Deployment success notification
        if: success()
        run: |
          echo "=========================================="
          echo "SUCCESS: Bot deployed to VPS"
          echo "=========================================="
          echo "Time: $(date '+%Y-%m-%d %H:%M:%S')"
          echo "Commit: ${{ github.sha }}"
          echo "Author: ${{ github.actor }}"
          echo "Branch: ${{ github.ref_name }}"
     
      - name: Deployment failure notification
        if: failure()
        run: |
          echo "=========================================="
          echo "FAILED: Bot deployment failed"
          echo "=========================================="
          echo "Time: $(date '+%Y-%m-%d %H:%M:%S')"
          echo "Commit: ${{ github.sha }}"
          echo "Author: ${{ github.actor }}"
          echo "Branch: ${{ github.ref_name }}"
          echo "Please check the logs above for details"


声明:本文仅用于技术交流与合法用途,禁止用于任何违反当地法律的行为。

本文由 网络资源分享 发布,如需转载请注明出处。

分享给朋友:
返回列表

上一篇:新买的vps先升级下系统最新的东西。

没有最新的文章了...

“GitHub Actions 让您轻松实现所有软件工作流程的自动化 CI/CD 功能。 实例代码” 的相关文章

用了机场后,这3件事千万不要做!务必要避免!

国内的互联网环境受到严格审查。俗称“防火墙”(Great Firewall)的机制,阻碍了境内用户访问大量境外网站和服务。许多人使用 虚拟私人网络(VPN)来绕过这一限制,从而访问如Twitter、YouTube、Google、Telegram等国际平台。然而,翻墙 ≠ 无限制自由。中国的...

为了注册tiktok~买了1张0月租的英国手机卡:GiffGaff卡

为了注册tiktok~买了1张0月租的英国手机卡:GiffGaff卡

经过这一次的 ChatGPT,突然意识到需要买一张外国卡专门注册外国的服务,少一些不确定性多一份安心,经过前辈们的推荐,选择了英国的 GiffGaff卡。该卡发行国家是英国,号码为英国段,希望大家了解自己的需求和业务是否合适。由于官网购买需要等待比较长的时间,我就直接在JD买了:查看购买链接本文主要...

TON 链上与 Telegram 深度绑定的三大资产玩法指南 TG匿名号码终极指南

一、TG 用户名(Telegram Username)1. 核心用途社交连接:无需电话号码,通过用户名即可添加联系人、加入公开群组或频道。社群运营:群组(Group):适合互动性强的社区,需选择易记的用户名便于用户搜索。频道(Channel):适合官方消息推送,用户名可增强品牌辨识度(如 @wall...

最热门的双币信用卡,免年费

最热门的双币信用卡,免年费

双币卡的用例是非常多的,无论是留学还是海淘,有着诸多的应用场景。我平时也会逛逛各类网站,一般的域名主机商都必须使用信用卡,例如甲骨文和谷歌云!还有就是注册其他地区的AppStore购买游戏应用等!双币信用卡可不仅仅可以支付美元,主流的欧元、日元、加币等都可以直接支付,还款日会按照当日汇率折算成人民币...

discuz x3.5 网站生成sitemap

使用说明将上述代码保存为 cron_sitemap.php 并上传到 Discuz! 的 source/include/cron/ 目录下在 Discuz! 后台添加计划任务:进入 后台 > 工具 > 计划任务 > 新增填写任务名称(如 &q...

WIN10+优化小工具 v1.3.1 - 果核剥壳

WIN10+优化小工具 v1.3.1 - 果核剥壳

一款聚合了系统快捷设置的小工具,一个界面就能完成常用设置的修改,使用之前,先点击读取本机设置避免数据错乱,然后根据需要勾选,完成后点击重启资源管理器即可。软件截图软件说明吾爱论坛 @辛卯易语言写的,可能存在误报毒的可能;每步操作透明显示放心使用;原帖地址:https://www.52pojie.cn...