如何在Jenkinsfile中ssh到服务器

xuo3flqw  于 2023-03-17  发布在  Jenkins
关注(0)|答案(3)|浏览(249)
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/到ssh到服务器的Jenkinsfile中,我的最终目标是ssh到服务器,从dockerhub拉取,构建,并把它放上去。
首先,我只想成功地进入它。
这个Jenkins文件给我WorkflowScript: 61: Expected a stage @ line 61, column 9. def remote = [:]
不确定这是否是正确的方法。如果有一种更简单的方法可以通过ssh进入服务器,并且像我手动执行命令一样执行命令,那么知道这一点也很好。
先谢了。

eiee3dmh

eiee3dmh1#

出现此错误的原因是语句def remote = [:]和后续赋值语句位于stage块之外。此外,由于声明性语法不支持直接位于steps块中的语句,因此还需要将该部分代码 Package 在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: '.'
        }
    }
}
sqxo8psd

sqxo8psd2#

此问题与插件无关,而是与管道的声明性语法有关。正如错误消息所述,需要一个阶段,但它找到了变量声明。
流水线需要包含阶段,阶段必须包含一个阶段。一个阶段必须有一个步骤....过去我浪费了很多天试图遵守严格的声明性语法,但现在不惜一切代价避免它。
尝试下面的简化脚本管道。

stage('Build React Image') {
    echo "stage1"
}
stage('Push React Image') {
    echo "stage2"
}
stage('Build Backend Image') {
    echo "stage3"
}
stage('Push Backend Image') {
     echo "stage4"
}
def remote = [:]
remote.name = '...'
remote.host = '...'
remote.user = '...'
remote.password = '...'
remote.allowAnyHosts = true
stage('SSH into the server') {
    writeFile file: 'abc.sh', text: 'ls -lrt'
    sshPut remote: remote, from: 'abc.sh', into: '.'
}
hgb9j2n6

hgb9j2n63#

ssh命令可在常规shell脚本中使用
示例:

pipeline {
    agent none

    stages {

        stage('Deploy') {
            options {
                /* do not pull the repository */
                skipDefaultCheckout()
            }
            environment {
                /* server IP */
                SERVER_IP = '8.8.8.8'
            }
            steps {
                sh '''
                    ssh $SERVER_IP "
                        echo Hello
                    "
                '''
            }
        } /* stage('Deploy') */

    }
}

相关问题