boolean linux shell_Jenkins 不能通过 root 操作 Linux 怎么办

由于公司的虚拟机只能通过域账户(LDAP)来登录,因此无法通过 root (root 不是 LDAP 域账户)账户来登录,这给 Jenkins 配置使用 Linux 的一些操作时带来很多不便。

cde66e8d22e42f765c0c75d0876898e1.png

如何解决

解决的办法有两种方式:一是在 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

欢迎评论

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值