Jenkins pipeline sh命令未引用正确的计算机

x33g5p2x  于 2023-01-25  发布在  Jenkins
关注(0)|答案(1)|浏览(160)

所以,我有以下管道

pipeline {
    agent any 

    environment {
      UPLOADED_FILES_DIR='/tmp/spring_fileupload_dir'
      DOCKER_USR=credentials('docker_usr')
      DOCKER_PASSWD=credentials('docker_passwd')
    }

    stages {
        stage('Test') { 
            steps {
                sh 'mvn test' 
            }
        }

        stage('Package') { 
            steps {
                sh 'mvn clean package -Dmaven.test.skip=true' 
            }
        }

        stage('Build') { 
            steps {
                sh """
                    docker build -t azold6/fileupload-pv-pvc:$BUILD_NUMBER . 
                """ 
            }
        }

        stage('Push') { 
            steps {
                sh """
                    docker login -u="$DOCKER_USR" -p="$DOCKER_PASSWD"
                    docker push azold6/fileupload-pv-pvc:$BUILD_NUMBER
                """ 
            }
        }

        stage('Deploy') { 
            steps {
                sshagent(credentials : ['key-to-ec2']) {
                    sh "docker run -d --name fileupload --rm azold6/fileupload-pv-pvc:$BUILD_NUMBER"
                }
            }
        }
    }
}

当我到达“Deploy”部分时,Jenkins显示以下错误:

docker: Error response from daemon: Conflict. The container name "/fileupload" is already in use by container "d7c3ee093de7a06c90e71db1bfc85df849ee218da3ae0cf59aa0bd733d9501e2". You have to remove (or rename) that container to be able to reuse that name.

问题是,容器“fileupload”正在Jenkins容器**中运行,而不是在目标EC2示例上运行。Jenkins引用了错误的机器,即使我使用的是SSH代理插件。
有什么办法解决吗?

n6lpvg4x

n6lpvg4x1#

我认为你混淆了两个不同插件的功能。
SSH Agent Plugin允许您通过Jenkins中的ssh-agent为构建提供SSH凭据,实际上是使用通用的withCredentials步骤将SSH私钥绑定到临时文件,然后将其传递给需要它的命令(例如,使用ssh或scp的-i选项)的缩写形式。
因此,这一步像其他插件一样在本地代理(节点)上执行shell命令。
实际上,您需要在远程计算机上运行shell命令,并使用提供的ssh凭据连接到该计算机。
要实现这一点,您需要使用SSH Pipeline StepsOfficial Site),这是Jenkins管道步骤,提供SSH工具,例如命令执行或向远程主机传输文件。
用法示例:

stage('Deploy') { 
    steps {
         script {
             withCredentials([sshUserPrivateKey(credentialsId: "key-to-ec2", keyFileVariable: 'sshKey', usernameVariable: 'sshUser')]) {
                 // Define the remote host configuration
                 def remote = [:];
                 remote.name = 'ec2-docker-host';
                 remote.host = '127.0.0.1';
                 remote.user = sshUser; 
                 remote.identifyFile = sshKey;
                 remote.allowAnyHosts = true;

                 // Once the remote host is defined, execute remote commands using the sshCommand step
                 sshCommand remote: remote, command: "ls -lrt"
                 sshCommand remote: remote, command: "for i in {1..5}; do echo -n \"Loop \$i \"; date ; sleep 1; done"
            } 
        }
    }
}

相关问题