在具有多个微服务的 monorepo 中使用 bitbucket 管道进行选择性服务部署

ain*_*sti 9 continuous-integration bitbucket continuous-deployment serverless-framework bitbucket-pipelines

我们有一个无服务器框架项目,在单一存储库中包含不同的微服务。该项目的结构如下所示:

project-root/
|-services/
  |-service1/
    |-handler.py
    |-serverless.yml
  |-service2/
  ...
  |-serviceN/
...
|-bitbucket-pipelines.yml
Run Code Online (Sandbox Code Playgroud)

如您所见,每个服务都有自己的部署文件(serverless.yml)。

我们只想部署在推送/合并中已修改的服务,并且由于我们使用的是 bitbucket-pipelines,所以我们更喜欢使用其功能来实现此目标。

经过一些研究后,我们发现了changesets可以限制目录中已更改文件的步骤的属性。因此,对于每项服务,我们可以在 bitbucket-pipelines.yml 中添加如下内容:

- step:
   name: step1
   script:
      - echo "Deploy service 1"
      - ./deploy service1
   condition:
      changesets:
         includePaths:
            # only files directly under service1 directory
            - "service1/**"
Run Code Online (Sandbox Code Playgroud)

这看起来是一个完美的匹配,但这种方法的问题是我们必须为存储库中的每个服务编写一个步骤,并且如果我们添加更多服务,我们将不得不添加更多步骤,这会影响可维护性和可读性。

有什么方法可以for使用参数化步骤进行循环,其中输入参数是服务名称?

另一方面,我们可以制作一个自定义脚本来处理条件并让部署本身检测更改。即使我们更喜欢 bitbucket-native 方法,我们也愿意接受其他选择;在脚本中执行此操作的最佳方法是什么?

N1n*_*ngu 0

最接近的方法是重用 yaml 锚点进行部署步骤,并将自定义部署环境与您的服务相匹配。

definitions:
  yaml-anchors:
    - &deploy-step
        name: Deploy
        script:
          - echo "Deploy $BITBUCKET_DEPLOYMENT_ENVIRONMENT"
          - ./deploy $BITBUCKET_DEPLOYMENT_ENVIRONMENT

pipelines:
  branches:
    main:
      - parallel:

        - step:
          <<: *deploy-step
          deployment: service1
          condition:
            changesets:
              includePaths:
                - service1/**

        - step:
          <<: *deploy-step
          deployment: service2
          condition:
            changesets:
              includePaths:
                - service2/**

        # ...

        - step:
          <<: *deploy-step
          deployment: serviceN
          condition:
            changesets:
              includePaths:
                - serviceN/**

Run Code Online (Sandbox Code Playgroud)

奖励:Bitbucket 将独立跟踪每个微服务部署。

我怀疑BITBUCKET_DEPLOYMENT_ENVIRONMENT是否可以在块中进行插值,includePaths所以这仍然相当冗长。如果您设法智能化您的部署脚本来检测文件更改,那么您可以将其减少为

definitions:
  yaml-anchors:
    - &deploy-step
        name: Deploy
        script:
          - echo "Deploy $BITBUCKET_DEPLOYMENT_ENVIRONMENT"
          - ./deploy $BITBUCKET_DEPLOYMENT_ENVIRONMENT

pipelines:
  branches:
    main:
      - parallel:

        - step:
          <<: *deploy-step
          deployment: service1
        - step:
          <<: *deploy-step
          deployment: service2
        # ...
        - step:
          <<: *deploy-step
          deployment: serviceN

Run Code Online (Sandbox Code Playgroud)

但请注意,您可以拥有的自定义部署环境的数量有限。