在 Jenkins 中“控制 Ubuntu 服务”一般指通过 Jenkins 启动 / 停止 / 重启 Ubuntu 上的 systemd 服务(如 nginx、spring boot、docker 服务等)。下面按常见场景给你讲清楚。
如果 Jenkins 就跑在这台 Ubuntu 上(或 Agent 在这台机器):
Jenkins Pipeline 示例
pipeline {
agent any
stages {
stage('Restart Service') {
steps {
sh '''
sudo systemctl restart my-service
systemctl status my-service
'''
}
}
}
}
Freestyle 项目
sudo systemctl restart my-service
Ubuntu 用 systemctl 需要 root 权限,而 Jenkins 默认用 jenkins 用户运行。
sudo visudo
添加一行(只给指定命令,安全):
jenkins ALL=(root) NOPASSWD: /bin/systemctl restart my-service
jenkins ALL=(root) NOPASSWD: /bin/systemctl status my-service
然后 Jenkins 里就能:
sudo systemctl restart my-service
写个脚本:
# /opt/scripts/restart-my-service.sh
#!/bin/bash
systemctl restart my-service
chmod +x /opt/scripts/restart-my-service.sh
sudoers:
jenkins ALL=(root) NOPASSWD: /opt/scripts/restart-my-service.sh
Jenkins:
sudo /opt/scripts/restart-my-service.sh
Pipeline 示例
stage('Deploy') {
steps {
sshCommand remote: [
name: 'ubuntu-server',
host: '192.168.1.100',
credentialsId: 'ssh-key',
allowAnyHost: true
], command: 'sudo systemctl restart my-service'
}
}
ssh ubuntu@192.168.1.100 "sudo systemctl restart my-service"
sudo systemctl restart docker
或 Jenkins 加入 docker 组(不推荐生产):
sudo usermod -aG docker jenkins
❌ Failed to connect to bus
❌ Permission denied
❌ Jenkins Agent 不是 Ubuntu
Jenkins 控 Ubuntu 服务 = shell + systemctl + 权限(sudo / SSH)
如果你告诉我:
我可以直接给你可复制的配置。