首页 > 解决方案 > 如何通过 ssh 进入 Jenkinsfile 中的服务器

问题描述

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: '.'
            }
        }
    }
}

我按照此页面上的文档:https://jenkins.io/doc/pipeline/steps/ssh-steps/在 Jenkinsfile 中通过 ssh 进入服务器。我的最终目标是通过 ssh 进入服务器,从 dockerhub 拉取,构建并安装。

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

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

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

提前致谢。

标签: jenkinssshjenkins-pipeline

解决方案


该错误是由于语句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: '.'
        }
    }
}

推荐阅读