You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bitbucket Pipeline锚点配置问题:仅单步执行且变量传递失败

问题:Bitbucket Pipeline锚点复用步骤失效+跨步骤变量传递

我写了两段Bitbucket Pipeline的YAML配置,想通过锚点复用步骤,但每次都只有setup_staging步骤被执行,换了另一种锚点合并写法结果还是一样。另外我还想在step_1里导出dev变量,在step_2里能用上,请问哪里配置错了?

第一段配置

# Define anchors for reuse
definitions:
  steps:
    - step: &setup_staging
        name: Setup staging deployment
        script:
          - echo "HelLo 1"

    - step: &terraform_plan
        name: Execute terraform init and plan
        script:
          - echo "HelLo 2"
    
infrastructure_plan_staging: &infrastructure_plan_staging
 - step: *setup_staging
 - step: *terraform_plan
 
pipelines:
  default:
    - <<: *infrastructure_plan_staging

第二段尝试的配置

infrastructure_plan_staging: &infrastructure_plan_staging
 <<: *setup_staging
 <<: *terraform_plan

解决方案

一、锚点复用步骤失效的修复

问题原因

  1. 第一段配置里,pipelines.default用- <<: *infrastructure_plan_staging是错误的——infrastructure_plan_staging本身就是一个步骤数组,直接引用数组不需要用YAML合并键<<:,这种写法会导致数组被当作单个对象处理,最终只执行第一个步骤。
  2. 第二段配置的写法更错:同一层级多个<<:会覆盖,最后只有最后一个锚点生效,而且步骤本身是数组结构,不能用合并键来叠加步骤。

正确写法

直接把步骤数组锚点赋值给pipelines.default即可:

# Define anchors for reuse
definitions:
  steps:
    - step: &setup_staging
        name: Setup staging deployment
        script:
          - echo "HelLo 1"

    - step: &terraform_plan
        name: Execute terraform init and plan
        script:
          - echo "HelLo 2"
    
infrastructure_plan_staging: &infrastructure_plan_staging
 - step: *setup_staging
 - step: *terraform_plan
 
pipelines:
  default: *infrastructure_plan_staging

二、跨步骤传递变量的配置

Bitbucket Pipeline的每个步骤都是独立容器,默认变量不共享,要传递动态生成的变量,推荐用**工件(artifacts)**的方式:

完整配置示例

# Define anchors for reuse
definitions:
  steps:
    - step: &setup_staging
        name: Setup staging deployment
        script:
          # 把变量写入脚本文件
          - echo "export DEV_VAR=my_dynamic_dev_value" > vars.sh
          - echo "HelLo 1"
        # 声明要传递到后续步骤的工件
        artifacts:
          - vars.sh
    
    - step: &terraform_plan
        name: Execute terraform init and plan
        script:
          # 加载变量脚本,获取之前定义的变量
          - source vars.sh
          # 使用变量
          - echo "DEV_VAR的值是:$DEV_VAR"
          - echo "HelLo 2"
    
infrastructure_plan_staging: &infrastructure_plan_staging
 - step: *setup_staging
 - step: *terraform_plan
 
pipelines:
  default: *infrastructure_plan_staging

原理说明

  1. 在setup_staging步骤中,将需要传递的变量写入一个shell脚本,通过artifacts字段标记这个文件为可传递的工件。
  2. 在后续的terraform_plan步骤中,用source命令加载这个脚本,就能获取到之前定义的变量。

如果是固定值变量,也可以直接在仓库的「Pipeline Variables」设置里配置,但动态生成的变量用工件方式更灵活。


内容的提问来源于stack exchange,提问作者Mornor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 23:43:43