首页 > 解决方案 > 从 jenkins SSH 到 ec2 并运行命令

问题描述

我正在尝试配置我的 Jenkinsfile,以便我的主 jenkins ssh 进入远程 ec2 服务器并在远程服务器上运行命令。到目前为止,我已将我的主 jenkins 服务器公钥添加到我的远程 ec2 服务器的 authorized_keys 列表中,并且我能够通过 ssh 进入我的远程服务器。我的 Jenkinsfile 的相关部分:

echo "===> about to SSH into the dev environment.."
        sh '''#!/bin/bash
          echo "===> in bash script now"
          ssh -tt ubuntu@xxx.xx.xx.xxx
          ls
          pwd          
          git pull origin master
          rm -rf node_modules
          npm install
          node app.js
        '''

我知道我能够 ssh 进入我的远程 ec2 实例,因为ls在我的远程服务器上打印文件的内容。

但是,pwd打印出来/var/lib/jenkins/workspace/jenkinsfile_master 这意味着我仍在我的 jenkins 主服务器上。此外,我的gitnpm命令不会运行,因为git并且npm没有安装在我的 Jenkins 主服务器上。

因此,我的第一个问题是我真的 ssh 到我的远程服务器吗?如果我这样做了,为什么要pwd在我的 Jenkins 服务器而不是我的远程服务器上打印工作目录?其次,如何才能真正在远程服务器上运行命令?

标签: amazon-web-servicesjenkinsamazon-ec2ssh

解决方案


推测您遇到的每个命令的行为都被单独调用到命令行(这意味着每个命令都作为不同的会话运行)。如果是这种情况,您需要在没有任何其他插件的情况下将它们全部链接起来,例如下面的示例。

ssh -tt ubuntu@xxx.xx.xx.xxx && ls && pwd && git pull origin master .....

有一个名为SSH Steps的 Jenkins 插件,它允许您运行每个命令,如下所示

sshCommand remote: remote, command: "ls"
sshCommand remote: remote, command: "pwd"
sshCommand remote: remote, command: "git pull origin master"

或者,如果您不想使用此插件,AWS 还有一个名为Run Command的功能,允许您使用 AWS CLI/SDK 在服务器上远程调用命令。有了这个,当您使用git pull命令时,您需要确保远程服务器的磁盘上存在凭据。


推荐阅读