温馨提示×

jenkins怎么控ubuntu服务

小樊
58
2026-10-24 21:17:19
栏目: 智能运维

在 Jenkins 中“控制 Ubuntu 服务”一般指通过 Jenkins 启动 / 停止 / 重启 Ubuntu 上的 systemd 服务(如 nginx、spring boot、docker 服务等)。下面按常见场景给你讲清楚。


一、最常见方式:Jenkins 执行 shell 控制 systemd 服务

1️⃣ Jenkins 节点能直接操作 Ubuntu

如果 Jenkins 就跑在这台 Ubuntu 上(或 Agent 在这台机器):

Jenkins Pipeline 示例

pipeline {
    agent any
    stages {
        stage('Restart Service') {
            steps {
                sh '''
                    sudo systemctl restart my-service
                    systemctl status my-service
                '''
            }
        }
    }
}

Freestyle 项目

  • Build → Execute shell
sudo systemctl restart my-service

二、关键问题:Jenkins 没权限控制服务(重点)

Ubuntu 用 systemctl 需要 root 权限,而 Jenkins 默认用 jenkins 用户运行。

✅ 方案 1:给 jenkins 用户 sudo 权限(最常用)

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

✅ 方案 2:使用 systemd 的 sudoers + 脚本封装(更安全)

写个脚本:

# /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

三、Jenkins 控制远程 Ubuntu 服务

方式 1:SSH 插件(推荐)

  1. Jenkins → Manage Jenkins → Plugins → 安装 SSH Pipeline Steps
  2. 配置 Credentials(SSH 私钥)

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'
    }
}

方式 2:ssh 命令(简单粗暴)

ssh ubuntu@192.168.1.100 "sudo systemctl restart my-service"

四、控制 Docker 服务(Ubuntu 常见)

sudo systemctl restart docker

或 Jenkins 加入 docker 组(不推荐生产):

sudo usermod -aG docker jenkins

五、服务没反应?常见坑

❌ Failed to connect to bus

  • Jenkins 在 Docker 容器中,没有 systemd ✅ 解决:控制宿主机服务,或用 SSH

❌ Permission denied

  • 没配置 sudo NOPASSWD

❌ Jenkins Agent 不是 Ubuntu

  • 服务命令要对应系统

六、总结一句话

Jenkins 控 Ubuntu 服务 = shell + systemctl + 权限(sudo / SSH)

如果你告诉我:

  • Jenkins 在本机还是远程?
  • 控制什么服务?
  • 用 Pipeline 还是 Freestyle?

我可以直接给你可复制的配置。

0 踩