我使用Jenkins来触发多个服务的部署(使用部署脚本)--总共有6个服务,并且使用Jenkins Boolean Parameter来选择要部署的服务。
因此,如果要部署第1、第4和第5服务,那么在Jenkins Execute shell选项卡中,部署脚本的输入如下所示。
#!/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个参数。有什么更好的方法来做呢?
发布于 2022-06-30 13:47:37
数组在这里会有帮助。
#!/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服务,那么远程脚本会将Hello和World作为两个单独的参数来处理,这可能不是您想要的。
如果这对您来说是个问题,您可以使用printf %q (大多数Bash支持)或将数组扩展为"${services_to_deploy[@]@Q}" (如果您有Bash4.4或更高版本)来解决这个问题。
使用printf %q的示例可能如下所示:
#!/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[@]}"发布于 2022-06-30 13:42:35
不如你改进你的脚本,并引入一些标志。
# --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}https://stackoverflow.com/questions/72816335
复制相似问题