【问题标题】:Jenkinsfile: connect to a server and perform operations on the serverJenkinsfile:连接到服务器并在服务器上执行操作
【发布时间】:2020-03-22 08:26:50
【问题描述】:

在 Jenkinsfile 中,我尝试登录服务器并从那里运行 docker-compose。但是,我收到AccessDeniedException 错误。 Root 用户拥有服务器上所有文件夹的权限。

我假设我有一个思维错误:我怀疑在 ssh 到服务器之后,dir 命令没有在服务器中运行,而是在运行 jenkins 的地方运行。

Jenkins 文件:

pipeline {
    agent any

    environment {
        PATH = "$PATH:/usr/local/bin/"
    }

    stages {

        stage('Deploy to digital ocean') {
            steps {
                sshagent(['my-private-ssh-key']) {

                    sh """
                            ssh root@host
                        """
                     dir("/var/www/car_prices"){
                        sh "docker-compose down"

                     }

                 }
            }

        }
    }
}

错误堆栈:

[Pipeline] dir
Running in /var/www/car_prices
[Pipeline] {
[Pipeline] sh
[Pipeline] }
[Pipeline] // dir
[Pipeline] }
$ ssh-agent -k
unset SSH_AUTH_SOCK;
unset SSH_AGENT_PID;
echo Agent pid 67144 killed;
[ssh-agent] Stopped.
[Pipeline] // sshagent
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.nio.file.AccessDeniedException: /var/www

问题: 1. 为什么会报错?

【问题讨论】:

  • 您的怀疑是正确的,dir 步骤在 Jenkins master 上运行。
  • @zett42 做我打算完成的事情的最佳方法是什么?

标签: jenkins docker-compose jenkins-pipeline jenkins-groovy


【解决方案1】:

您需要使用ssh 为您完成这项工作,这相当简单:

...
sshagent(['my-private-ssh-key']) {
    sh """
        ssh root@host "cd /var/www/car_prices; docker-compose down"
    """
}
...

这有点难看,但有效。如果您愿意,可以将命令拆分为多行以获得更好的可读性。如果您想提供一些更复杂的功能,例如错误处理,这种方法会变得更加棘手。

【讨论】:

  • 什么是不丑陋的做法?
  • 不知道有没有。我按照上面的方法做,它对我有用。如果命令在从机上执行会更好看(所以如果你的主机是从机),但它并不总是一个选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-21
相关资源
最近更新 更多