由于公司的虚拟机只能通过域账户(LDAP)来登录,因此无法通过 root (root 不是 LDAP 域账户)账户来登录,这给 Jenkins 配置使用 Linux 的一些操作时带来很多不便。
![cde66e8d22e42f765c0c75d0876898e1.png](https://i-blog.csdnimg.cn/blog_migrate/5fa22488ca4e4abd763735760f71d32e.jpeg)
如何解决
解决的办法有两种方式:一是在 Jenkins 上解决,二是在 Linux 上来解决。
在 Jenkins 解决
在 Jenkins 端来解决,我找到 Jenkins 有这样一个插件SSH Pipeline Steps https://jenkins.io/doc/pipeline/steps/ssh-steps/ 看了下具体的参数:
def remote = [:]remote.name = 'test'remote.host = 'test.domain.com'remote.user = 'root'remote.password = 'password'remote.allowAnyHosts = truestage('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 上解决
常用的办法就是把 sudo 时候不需要输入密码的账户如下添加到 visodu 文件里
// open a shell console and type$ sudo visudo// type your user namejenkins ALL=(ALL) NOPASSWD: ALL
但即使这样设置,通过 Jenkins 执行 shell 脚本的时候还是出现如下问题
sudo: no tty present and no askpass program specified
最终调查的原因还是跟公司的 LDAP 设置有关,使用不允许用户无需输入密码,这种办法也不适合我。
最终解决办法
那我只能在 sudo 的时候,真实的输入密码了。查查 sudo 的帮助,我看到有这样一个参数 -S,这个参数可以从标准输入进行读取。
sudo --help-S, --stdin read password from standard input
这样我把密码放到 Jenkinsfile 的 credentials 里,然后再读取这个密码在 sudo 时候进行标准输入,最终通过如下代码实现了在 Jenkins Agent 上使用 sudo 实现 root 操作。
// Jenkinsfileenvironment { JENKINS = credentials("d1cbab74-823d-41aa-abb7-85848595")}sh 'sudo -S <<< "$JENKINS_PSW" sh test.sh'
![2feff66acf4d1f0457395d3648cc69dd.png](https://i-blog.csdnimg.cn/blog_migrate/4be96cef6d63a3dce83cea10a7517212.jpeg)
欢迎评论
如果你有更好的方式,欢迎留言评论,谢谢。