跳过正文
  1. Posts/

在 Jenkins pipeline 中执行 sudo 的时候不需要输入密码

·331 字·1 分钟· ·
沈显鹏
作者
沈显鹏

在使用 Jenkins pipeline 的时候,在 Linux 需要用 root 来执行,我想通过 Jenkins pipeline 的语法来解决,但是只找到这种方式:SSH Pipeline Steps

def remote = [:]
remote.name = 'test'
remote.host = 'test.domain.com'
remote.user = 'root'
remote.password = 'password'
remote.allowAnyHosts = true
stage('Remote SSH') {
    sshCommand remote: remote, command: "ls -lrt"
    sshCommand remote: remote, command: "for i in {1..5}; do echo -n \"Loop \$i \"; date ; sleep 1; done"
}

* command
    * Type: String
* dryRun (optional)
    * Type: boolean
* failOnError (optional)
    * Type: boolean
* remote (optional)
    * Nested Choice of Objects
* sudo (optional)
    * Type: boolean

从 example 来看需要提供的参数比较多,很多参数我已经在 Pipeline 的 environment 已经设置过了,这里再设置就显得不够优美,且限于没有足够的 example,你知道的 Jenkinsfile 调试非常痛苦和麻烦,我就没通过这种方式来尝试解决。

通过 Linux 设置来解决

// open a shell console and type
$ sudo visudo

// type your user name
jenkins ALL=(ALL) NOPASSWD: ALL

但即使这样设置,通过 Jenkins 执行 shell 脚本的时候还是出现如下问题

sudo: no tty present and no askpass program specified

最后通过如下脚本解决了我的问题

// Jenkinsfile

environment {
    JENKINS = credentials("d1cbab74-823d-41aa-abb7-85848595")
}

sh 'sudo -S <<< "$JENKINS_PSW" sh test.sh'

如果你有更好的方式,欢迎留言评论,谢谢。

相关文章

Jenkinsfile example - 实现交互、clone 多个仓库以及 git push
·416 字·1 分钟
这个 Jenkinsfile 示例展示了如何在 Jenkins Pipeline 中实现交互式输入、克隆多个 Git 仓库,并在构建完成后将代码推送到远程仓库。
GitSCM clone code don't display branch
·546 字·2 分钟
如何在 Jenkins 中使用 GitSCM插件克隆代码时,确保正确显示分支信息,避免出现 HEAD detached 状态的问题。
Jenkins Linux Agent 配置
·353 字·1 分钟
本文提供了 Jenkins Linux Agent 的逐步配置指南,包括 Java 运行时的准备、节点创建以及常见问题的排查方法。
Jenkins Windows Agent 配置
·608 字·2 分钟
本文提供 Jenkins Windows Agent 的详细配置步骤,包括 Java 运行时准备、节点创建以及常见问题的排查方法。
Jenkinsfile 配置
·256 字·1 分钟
本文介绍了如何使用 Jenkinsfile 配置 Jenkins Pipeline,包括构建、测试和发布阶段的示例,以及如何处理邮件通知。
通过参数化上传文件到 FTP 服务器
·359 字·1 分钟
本文介绍了如何使用 Windows Batch 脚本通过参数化的方式上传文件到 FTP 服务器,避免在脚本中硬编码 FTP 凭据。