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

如何利用Bitbucket Pipeline条件进入指定目录执行Terraform命令?

基于Bitbucket Pipeline实现多环境Terraform目录变更触发执行

核心思路是利用Bitbucket Pipeline的changesets条件检测目标环境目录的文件变更,为每个环境单独定义执行步骤,仅当对应目录有变更时触发该步骤,再进入目录执行Terraform命令。

完整配置示例

以下是适配你的仓库结构的bitbucket-pipelines.yml配置:

# 使用官方Terraform镜像,省去依赖安装步骤
image: hashicorp/terraform:latest

# 定义Terraform依赖缓存,加速init过程
definitions:
  caches:
    terraform: .terraform

pipelines:
  # 默认分支(如develop)的执行流程
  default:
    - parallel:
        # 开发环境Terraform计划
        - step:
            name: 开发环境Terraform Plan
            condition:
              changesets:
                includePaths:
                  - "infra/develop/**" # 匹配开发目录下所有文件/子目录变更
            cache: terraform
            script:
              - cd infra/develop
              - terraform init -input=false # 禁用交互式输入,适配CI环境
              - terraform validate # 提前校验语法
              - terraform plan -input=false -out=plan.tfplan # 生成执行计划文件

        # 预发布环境Terraform计划
        - step:
            name: 预发布环境Terraform Plan
            condition:
              changesets:
                includePaths:
                  - "infra/staging/**"
            cache: terraform
            script:
              - cd infra/staging
              - terraform init -input=false
              - terraform validate
              - terraform plan -input=false -out=plan.tfplan

  # 主分支(生产环境)的执行流程
  branches:
    main:
      - step:
          name: 生产环境Terraform Plan
          condition:
            # 同时满足:主分支 + 生产目录变更
            and:
              - changesets:
                  includePaths:
                    - "infra/prod/**"
              - branch: main
          cache: terraform
          script:
            - cd infra/prod
            - terraform init -input=false
            - terraform validate
            - terraform plan -input=false -out=plan.tfplan

      - step:
          name: 生产环境Terraform Apply
          condition:
            changesets:
              includePaths:
                - "infra/prod/**"
          cache: terraform
          script:
            - cd infra/prod
            - terraform init -input=false
            - terraform apply -input=false plan.tfplan
          trigger: manual # 手动触发生产环境变更,避免误操作

关键配置说明

  1. 变更检测:通过changesets.includePaths使用**通配符精准匹配目标环境目录下的所有变更,只有符合条件的变更才会触发对应步骤。
  2. 多环境隔离:每个环境步骤独立切换到对应目录执行命令,确保Terraform状态文件和配置互不干扰(建议为每个环境配置独立的后端存储,如S3)。
  3. 生产环境安全:主分支的生产环境Apply步骤设置为手动触发,必须经过人工确认才能执行变更,降低风险。
  4. 缓存优化:配置terraform缓存,复用依赖包,减少init步骤的执行时间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:35:17