如何在Jenkinsfile中ssh到服务器

xuo3flqw  于 2023-03-17  发布在  Jenkins
关注(0)|答案(3)|浏览(305)
  1. pipeline {
  2. agent any
  3. stages {
  4. stage('Build React Image') {
  5. steps {
  6. ...
  7. }
  8. }
  9. stage('Push React Image') {
  10. steps {
  11. ...
  12. }
  13. }
  14. stage('Build Backend Image') {
  15. steps {
  16. ...
  17. }
  18. }
  19. stage('Push Backend Image') {
  20. steps {
  21. ...
  22. }
  23. }
  24. def remote = [:]
  25. remote.name = '...'
  26. remote.host = '...'
  27. remote.user = '...'
  28. remote.password = '...'
  29. remote.allowAnyHosts = true
  30. stage('SSH into the server') {
  31. steps {
  32. writeFile file: 'abc.sh', text: 'ls -lrt'
  33. sshPut remote: remote, from: 'abc.sh', into: '.'
  34. }
  35. }
  36. }
  37. }

我遵循了此页面上的文档: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块中。

  1. stage('SSH into the server') {
  2. steps {
  3. script {
  4. def remote = [:]
  5. remote.name = '...'
  6. remote.host = '...'
  7. remote.user = '...'
  8. remote.password = '...'
  9. remote.allowAnyHosts = true
  10. writeFile file: 'abc.sh', text: 'ls -lrt'
  11. sshPut remote: remote, from: 'abc.sh', into: '.'
  12. }
  13. }
  14. }
sqxo8psd

sqxo8psd2#

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

  1. stage('Build React Image') {
  2. echo "stage1"
  3. }
  4. stage('Push React Image') {
  5. echo "stage2"
  6. }
  7. stage('Build Backend Image') {
  8. echo "stage3"
  9. }
  10. stage('Push Backend Image') {
  11. echo "stage4"
  12. }
  13. def remote = [:]
  14. remote.name = '...'
  15. remote.host = '...'
  16. remote.user = '...'
  17. remote.password = '...'
  18. remote.allowAnyHosts = true
  19. stage('SSH into the server') {
  20. writeFile file: 'abc.sh', text: 'ls -lrt'
  21. sshPut remote: remote, from: 'abc.sh', into: '.'
  22. }
展开查看全部
hgb9j2n6

hgb9j2n63#

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

  1. pipeline {
  2. agent none
  3. stages {
  4. stage('Deploy') {
  5. options {
  6. /* do not pull the repository */
  7. skipDefaultCheckout()
  8. }
  9. environment {
  10. /* server IP */
  11. SERVER_IP = '8.8.8.8'
  12. }
  13. steps {
  14. sh '''
  15. ssh $SERVER_IP "
  16. echo Hello
  17. "
  18. '''
  19. }
  20. } /* stage('Deploy') */
  21. }
  22. }
展开查看全部

相关问题