如何在BitBucket Pipelines中避免master与development分支的部署代码重复?
Reusing BitBucket Pipeline Steps for Multiple Branches with YAML Anchors
Absolutely! You can use YAML anchors and aliases to avoid duplicating your deployment script logic across branches. The key is to define a reusable base configuration anchor that contains all the shared logic, then reference it in each branch while overriding only the differences (like the deployment environment, step name, and branch-specific paths).
Here's a clean, working refactor of your script:
# Define a reusable anchor for core deployment logic (shared across branches) &base_deployment trigger: manual script: - pipe: atlassian/scp-deploy:1.0.1 variables: USER: $DOMAIN SERVER: $SERVER LOCAL_PATH: 'dist/*' branches: master: - step: name: Deployment to production deployment: production <<: *base_deployment script: # Merge base variables + add production-specific path - pipe: atlassian/scp-deploy:1.0.1 variables: <<: *base_deployment.script[0].variables REMOTE_PATH: '~/public/prod' development: - step: name: Deployment to development deployment: development <<: *base_deployment script: # Merge base variables + add development-specific path - pipe: atlassian/scp-deploy:1.0.1 variables: <<: *base_deployment.script[0].variables REMOTE_PATH: '~/public/dev'
Breakdown of how this works:
- Anchor Setup: The
&base_deploymentanchor stores all shared configuration (manual trigger, SCP pipe with common variables likeUSERandSERVER). This way, you only maintain this logic once. - Alias Reference: The
<<: *base_deploymentsyntax merges the base configuration into each branch's step, so you don't have to rewrite the entire script block. - Override Differences: We only specify what changes per branch: the step name,
deploymentenvironment (to pull the correct BitBucket variables), andREMOTE_PATHfor the target server directory.
If you ever need to update shared logic (like changing the SCP pipe version or adjusting a common variable), you only modify the anchor definition—all branches will inherit the change automatically.
内容的提问来源于stack exchange,提问作者Bas van Dijk
相关产品推荐
相关产品推荐

