如何在 Jenkinsfile 中 ssh 到服务器

Daw*_*n17 3 ssh jenkins jenkins-pipeline

pipeline {
    agent any
    stages {
        stage('Build React Image') {
            steps {
                ...
            }
        }
        stage('Push React Image') {
            steps {
                ...
            }
        }
        stage('Build Backend Image') {
            steps {
                ...
            }
        }
        stage('Push Backend Image') {
            steps {
                ...
            }
        }
        def remote = [:]
        remote.name = '...'
        remote.host = '...'
        remote.user = '...'
        remote.password = '...'
        remote.allowAnyHosts = true
        stage('SSH into the server') {
            steps {
                writeFile file: 'abc.sh', text: 'ls -lrt'
                sshPut remote: remote, from: 'abc.sh', into: '.'
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我按照此页面上的文档进行操作:https://jenkins.io/doc/pipeline/steps/ssh-steps/以 SSH 方式连接到 Jenkinsfile 中的服务器。我的最终目标是 ssh 进入服务器,从 dockerhub 拉取,构建并安装。

首先,我只想成功 ssh 进入它。

这个 Jenkinsfile 给了我WorkflowScript: 61: Expected a stage @ line 61, column 9. def remote = [:]

不确定这是否是正确的方法。如果有一种更简单的方法来 ssh 进入服务器并像我手动执行命令一样执行命令,那也很高兴知道。

提前致谢。

Dib*_*tya 5

该错误是由于语句def remote = [:]和后续赋值位于stage块之外而引起的。此外,由于声明性语法不支持直接在steps块内执行语句,因此您还需要将这部分代码包装在script块内。

stage('SSH into the server') {
    steps {
        script {
            def remote = [:]
            remote.name = '...'
            remote.host = '...'
            remote.user = '...'
            remote.password = '...'
            remote.allowAnyHosts = true
            writeFile file: 'abc.sh', text: 'ls -lrt'
            sshPut remote: remote, from: 'abc.sh', into: '.'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)