通过master下发脚本批量修改minion_id,以修改为IP为例
通过cmd.script远程执行shell脚本修改minion_id,步骤如下:
# 下发脚本并执行
>> salt 'old_minion_id' cmd.script salt://modify_minion_id.sh saltenv=dev
#输出结果
old_minion_id:
Minion did not return. [Not connected]
ERROR: Minions returned with non-zero exit code
# minion端日志modify_minion_id.log
2025-02-26 10:41:54 - ========== 开始修改 minion_id ==========
2025-02-26 10:41:54 - 备份 /etc/salt/minion_id 到 /etc/salt/minion_id.bak 成功.
2025-02-26 10:41:54 - 已将 /etc/salt/minion_id 修改为 IP: xx.xx.xx.xx
2025-02-26 10:41:54 - 正在重启 salt-minion 服务...
2025-02-26 10:43:24 - salt-minion 服务重启成功.
2025-02-26 10:43:29 - 执行 salt-call test.ping 检查通信...
2025-02-26 10:43:31 - 通信测试成功: local:
True
2025-02-26 10:43:31 - ========== 修改 minion_id 任务完成 ==========
# 檢查minion_id是否修改成功
>> salt xx.xx.xx.xx test.ping
>> salt xx.xx.xx.xx grains.get id
# 刪除舊的salt key
>> salt-key -y -d old_minion_id
modify_minion_id.sh
#!/bin/bash
# 定义日志文件
LOGFILE="/etc/salt/modify_minion_id.log"
# 定义日志输出函数,带时间戳
log() {
local msg="$1"
echo "$(date +"%Y-%m-%d %H:%M:%S") - ${msg}" | tee -a "${LOGFILE}"
}
log "========== 开始修改 minion_id =========="
# 1. 备份 /etc/salt/minion_id 文件
if [ -f /etc/salt/minion_id ]; then
cp /etc/salt/minion_id /etc/salt/minion_id.bak
if [ $? -eq 0 ]; then
log "备份 /etc/salt/minion_id 到 /etc/salt/minion_id.bak 成功."
else
log "备份 /etc/salt/minion_id 失败."
exit 1
fi
else
log "文件 /etc/salt/minion_id 不存在,跳过备份步骤."
fi
# 2. 修改 minion_id 文件为本机 IP
IP=$(hostname -I | awk '{print $1}')
if [ -n "$IP" ]; then
echo "$IP" > /etc/salt/minion_id
if [ $? -eq 0 ]; then
log "已将 /etc/salt/minion_id 修改为 IP: $IP"
else
log "修改 /etc/salt/minion_id 失败."
exit 1
fi
else
log "获取 IP 地址失败."
exit 1
fi
# 3. 延时并后台重启 salt-minion 服务,必須使用後台啟動
log "计划10秒后后台重启 salt-minion 服务..."
nohup bash -c "sleep 10; systemctl restart salt-minion" >/dev/null 2>&1 &
# 等待几秒钟,确保服务启动稳定
log "等待15s,確保服務啟動穩定..."
sleep 15
# 4. 执行 salt-call test.ping 检查与 master 通信是否正常
log "执行 salt-call test.ping 检查通信..."
PING_RESULT=$(salt-call test.ping 2>&1)
if echo "$PING_RESULT" | grep -q "True"; then
log "通信测试成功: $PING_RESULT"
else
log "通信测试失败: $PING_RESULT"
fi