首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >有效处理多个参数

有效处理多个参数
EN

Stack Overflow用户
提问于 2022-06-30 13:04:16
回答 2查看 43关注 0票数 0

我使用Jenkins来触发多个服务的部署(使用部署脚本)--总共有6个服务,并且使用Jenkins Boolean Parameter来选择要部署的服务。

因此,如果要部署第1、第4和第5服务,那么在Jenkins Execute shell选项卡中,部署脚本的输入如下所示。

代码语言:javascript
复制
#!/bin/bash
sshpass -p <> ssh  username@host "copy the deployment script to the deployment VM/server and give execute persmission...."
sshpass -p <> ssh  username@host "./mydeploy.sh  ${version_to_be_deployed} ${1st_service} ${4th_service} ${5th_service}"

注意:部署发生在访问权限非常有限的不同服务器上,因此必须将部署脚本- mydeploy.sh从Jenkins奴隶复制到部署服务器,然后使用相应的参数执行。

如何使这个设置更加健壮和优雅。如果选择了所有6个服务,我不想传递6个参数。有什么更好的方法来做呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-06-30 13:47:37

数组在这里会有帮助。

代码语言:javascript
复制
#!/bin/bash
#hardcoded for demo purposes, but you can build dynamically from arguments
services_to_deploy=( 1 4 5 ) 
sshpass -p <> ssh  username@host "copy the deployment script to the deployment VM/server and give execute persmission...."
sshpass -p <> ssh  username@host "./mydeploy.sh  ${version_to_be_deployed} ${services_to_deploy[@]}"

${services_to_deploy[@]}将扩展到您想要部署的所有服务的列表,这样您就不必为每个服务设置唯一的变量。

但是,一个警告是,在ssh上运行命令类似于使用eval运行命令,因为远程shell将在执行之前对任何经过的内容进行分析。如果您的服务有简单的名称--这可能无关紧要,但是如果您有一个假设的Hello World服务,那么远程脚本会将HelloWorld作为两个单独的参数来处理,这可能不是您想要的。

如果这对您来说是个问题,您可以使用printf %q (大多数Bash支持)或将数组扩展为"${services_to_deploy[@]@Q}" (如果您有Bash4.4或更高版本)来解决这个问题。

使用printf %q的示例可能如下所示:

代码语言:javascript
复制
#!/bin/bash
services_to_deploy=( 1 4 5 )
remote_arguments=()
for s in "${services_to_deploy[@]}" ; do
  remote_arguments+=( "$( printf '%q' "${s}" )" )
done
sshpass -p <> ssh  username@host "copy the deployment script to the deployment VM/server and give execute persmission...."
sshpass -p <> ssh  username@host "./mydeploy.sh  ${version_to_be_deployed} ${remote_arguments[@]}"
票数 1
EN

Stack Overflow用户

发布于 2022-06-30 13:42:35

不如你改进你的脚本,并引入一些标志。

代码语言:javascript
复制
# --all : Deploys all services
./mydeploy.sh --version 1.0 --all

# --exclude : Deploys all services other than 5th_service and 4th_service (Excludes 4th and 5th)
./mydeploy.sh --version 1.0 --exclude ${5th_service} ${4th_service}

# --include : Deploys just  4th_service and 5th_service
./mydeploy.sh --version 1.0 --include ${5th_service} ${4th_service}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72816335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档