在 Jenkins 中“管理 CentOS 服务”,通常有以下几种常见场景和需求。我按最常用、最实用的方式给你系统讲一下。
适用场景:Jenkins 在一台机器,CentOS 服务在另一台(或本机)
Jenkins 插件管理 → 安装:
Jenkins:
pipeline {
agent any
stages {
stage('Restart Service') {
steps {
sshagent(['centos-ssh']) {
sh '''
ssh user@centos-ip <<'EOF'
sudo systemctl restart nginx
sudo systemctl status nginx
EOF
'''
}
}
}
}
}
⚠️ 注意:
sshd适用场景:Jenkins 直接装在 CentOS 上
visudo
添加:
jenkins ALL=(ALL) NOPASSWD: /bin/systemctl
stage('Restart Service') {
steps {
sh 'sudo systemctl restart httpd'
}
}
systemctl start xxx
systemctl stop xxx
systemctl restart xxx
systemctl enable xxx
systemctl status xxx
sh '''
sudo systemctl restart myapp
sudo systemctl status myapp --no-pager
'''
Jenkins 只做调度,Ansible 做服务管理
stage('Deploy') {
steps {
sh 'ansible centos -m systemd -a "name=nginx state=restarted"'
}
}
✅ 优点:
❌ Jenkins 用户无 sudo
❌ SSH 没配置密钥
❌ CentOS 防火墙/SELinux 拦截
❌ systemctl 在非 root 下失败
为了给你更精确方案,可以补充:
我可以直接帮你写完整 Jenkins 配置。