如何在Bitbucket Pipelines中实现集成测试失败时自动回滚部署?
问题描述
已在Bitbucket Pipelines中配置了单元测试与集成测试环节。部署代码前,流水线会先执行单元测试,若测试失败则不会进行部署,相关流水线配置如下:
.build_&_test_template: &build_test_template | nvm install 18 nvm use 18 npm ci npm run coverage pipelines: branches: uat: - step: name: Deploy to UAT deployment: test script: - *build_test_template - *shared_deploy_template
若npm run coverage未通过Jasmine测试配置的条件,则代码不会进入shared_deploy_template环节。
之后添加了部署完成(即shared_deploy_template执行后)的集成测试环节,配置如下:
.shared_postman_test_template: &shared_postman_test_template | npm run postmanTests pipelines: branches: uat: - step: ... script: - *build_test_template - *shared_deploy_template - *shared_postman_test_template
现在希望当shared_postman_test_template执行失败时,能够自动回滚已完成的部署。请问是否有办法基于测试条件实现部署的自动回滚?
实现方案
完全可以实现,核心思路是在集成测试失败时触发回滚逻辑,具体配置方式如下:
- 定义回滚模板
先创建一个包含UAT环境回滚命令的模板,回滚逻辑需要匹配你的实际部署方式(比如恢复镜像版本、回滚配置、重启服务等):
.shared_rollback_template: &shared_rollback_template | # 替换为你的实际回滚命令,示例如下: # npm run rollback-uat # kubectl rollout undo deployment/uat-service echo "Executing UAT deployment rollback..."
- 修改流水线脚本,添加失败判断
在原有步骤中加入条件判断:执行集成测试后,若测试失败则调用回滚模板,同时保持流水线的失败状态:
.build_&_test_template: &build_test_template | nvm install 18 nvm use 18 npm ci npm run coverage .shared_deploy_template: &shared_deploy_template | # 你的原有部署命令 echo "Deploying to UAT environment..." .shared_postman_test_template: &shared_postman_test_template | npm run postmanTests .shared_rollback_template: &shared_rollback_template | # 替换为实际回滚命令 echo "Rolling back UAT deployment to previous stable version..." pipelines: branches: uat: - step: name: Build, Test, Deploy & Verify deployment: test script: - *build_test_template - *shared_deploy_template # 执行集成测试,失败则触发回滚 - if ! eval "$(echo *shared_postman_test_template)"; then eval "$(echo *shared_rollback_template)"; exit 1; # 确保流水线标记为失败 fi
- 关键注意事项
- 回滚脚本需保证幂等性:多次执行不会引发额外异常
- 确保Pipeline拥有UAT环境的操作权限:比如服务器登录权限、部署工具的执行权限等
- 提前单独测试回滚逻辑:验证其能正确恢复到部署前的稳定状态
内容的提问来源于stack exchange,提问作者Jarede
相关产品推荐
相关产品推荐

