自动化脚本

最近也有负责了一些运维部署的工作,每次发包都比较麻烦,编写了一个自动化脚本
大概思路是从 github 上拉取对应分支代码到本地,本地编译,复制拷贝到目标目录,启动执行
注意最后要赋予文件可执行权限

#!/bin/bash

# Prompt user for environment
echo "Enter environment (dev, test, or prod): "
read ACTIVE

# Check if the input is valid
if [ "$ACTIVE" != "dev" ] && [ "$ACTIVE" != "test" ] && [ "$ACTIVE" != "prod" ]; then
    echo "Invalid environment choice. Exiting."
    exit 1
fi

# Prompt user for Git branch
echo "Enter Git branch name: "
read BRANCH

BASE_PATH="/opt/watchx/$ACTIVE"
JAR_FILE="aaa-0.0.1-SNAPSHOT.jar"       # JAR 文件路径
PID_FILE="pid"                             # PID 文件路径
REPO_PATH="/opt/code_repo/aaa"          # Git 仓库路径

# 如果仓库目录存在,先删除它
if [ -d "$REPO_PATH" ]; then
    rm -rf "$REPO_PATH"
    echo "Deleted existing repository directory: $REPO_PATH"
fi

# 克隆新的仓库到指定目录 需要修改
GIT_URL="https://${GITHUB_PAT}@github.com/path1/code.git"
git clone "$GIT_URL" "$REPO_PATH"


# 移动到 Git 仓库目录
cd "$REPO_PATH" || exit 1

# 检查分支是否存在
if ! git ls-remote --heads origin "$BRANCH" | grep -q "$BRANCH"; then
    echo "Branch '$BRANCH' does not exist. Exiting."
    exit 1
fi

# 拉取指定分支并更新代码
git fetch origin
git checkout "$BRANCH"
git pull origin "$BRANCH"

# 执行 Maven 打包,跳过测试
mvn clean package -Dmaven.test.skip=true

# 备份原来的 JAR 文件
if [ -f "$BASE_PATH/$JAR_FILE" ]; then
    TIMESTAMP=$(date +"%Y%m%d%H%M%S")
    mv "$BASE_PATH/$JAR_FILE" "$BASE_PATH/$JAR_FILE.bak.$TIMESTAMP"
    echo "Backup original JAR file to $BASE_PATH/$JAR_FILE.bak.$TIMESTAMP"
fi

# 拷贝新的 JAR 文件到目标目录
cp "$REPO_PATH/target/$JAR_FILE" "$BASE_PATH/"
echo "Copied new JAR file to $BASE_PATH/$JAR_FILE"

# 移动到目标目录
cd "$BASE_PATH" || exit 1

# 检查 PID 文件是否存在
if [ -f "$PID_FILE" ]; then
    # 读取 PID
    PID=$(cat "$PID_FILE")
    if [ -n "$PID" ] && [ -d "/proc/$PID" ]; then
        echo "Killing existing process with PID: $PID"
        kill "$PID"
        sleep 5 # 等待进程终止
        # 再次检查进程是否已终止
        if [ -d "/proc/$PID" ]; then
            echo "Process $PID did not terminate. Forcing termination."
            kill -9 "$PID"
        fi
    fi
fi

# 启动新的进程
echo "Starting new Java process"
nohup java -Xms4g -Xmx4g -Dspring.profiles.active="$ACTIVE" -jar "$JAR_FILE" > cccc.log 2>&1 &

# 获取新进程的 PID
NEW_PID=$!
echo "New process PID: $NEW_PID"

# 将新进程的 PID 写入 PID 文件
echo "$NEW_PID" > "$PID_FILE"
echo "PID saved to $PID_FILE"

tail -1000f cccc.log

这是一段防爬代码块,我不介意文章被爬取,但请注明出处
console.log("作者主页:https://www.cnblogs.com/Go-Solo");
console.log("原文地址:https://www.cnblogs.com/Go-Solo/p/18329650");
posted @ 2024-07-29 11:01  Go_Solo  阅读(32)  评论(0编辑  收藏  举报