如何在Shell脚本中执行deploy.sh并调用Jenkins withCredentials插件?
实现方案:Jenkins withCredentials 配合 deploy.sh 执行
1. 核心逻辑
withCredentials插件的作用是在Jenkins流水线的特定阶段注入敏感凭据(用户名密码、SSH密钥、令牌等),这些凭据会以环境变量或临时文件的形式暴露给后续Shell操作。你只需要让deploy.sh脚本读取这些注入的凭据,就能完成带权限验证的部署操作。
2. 具体实现示例
场景1:传递用户名密码凭据
如果deploy.sh需要用户名密码登录镜像仓库、数据库等,可按以下方式配置流水线:
pipeline { agent any stages { stage('Run Deployment') { steps { withCredentials([usernamePassword( credentialsId: 'your-credential-id', // Jenkins凭据管理中配置的ID usernameVariable: 'DEPLOY_USER', // 注入的用户名环境变量名 passwordVariable: 'DEPLOY_PASS' // 注入的密码环境变量名 )]) { // 执行deploy.sh,脚本内可直接调用这两个环境变量 sh './deploy.sh' } } } } }
对应的deploy.sh读取凭据的片段:
#!/bin/bash # 使用注入的环境变量完成登录操作 docker login your-registry.example.com -u $DEPLOY_USER -p $DEPLOY_PASS # 后续部署步骤...
场景2:传递SSH私钥凭据
如果deploy.sh需要通过SSH连接目标服务器,用file类型的凭据注入私钥:
pipeline { agent any stages { stage('Deploy via SSH') { steps { withCredentials([sshUserPrivateKey( credentialsId: 'your-ssh-cred-id', keyFileVariable: 'SSH_KEY_PATH', // 私钥文件路径的环境变量 usernameVariable: 'SSH_USER' // SSH登录用户名 )]) { sh ''' # 修正私钥文件权限(避免SSH因权限过宽报错) chmod 600 $SSH_KEY_PATH # 执行deploy.sh,脚本内用$SSH_KEY_PATH指定私钥 ./deploy.sh ''' } } } } }
deploy.sh中使用私钥的片段:
#!/bin/bash # 通过指定私钥连接目标服务器执行部署命令 ssh -i $SSH_KEY_PATH $SSH_USER@target-server "mkdir -p /app && cp ./dist/* /app"
3. 关键注意事项
- 确保Jenkins已安装Credentials Binding Plugin(withCredentials依赖的核心插件)
- 凭据ID必须与Jenkins凭据管理中配置的完全一致
- 执行前给deploy.sh添加可执行权限:
chmod +x deploy.sh - 凭据仅在
withCredentials代码块内有效,不要在块外引用相关变量 - 不要在脚本或日志中明文输出敏感凭据,Jenkins会自动屏蔽插件注入的敏感变量,但自定义脚本也要避免打印密码/密钥内容
内容的提问来源于stack exchange,提问作者learn_allot
相关产品推荐
相关产品推荐

