Trigger Gitlab Pipeline Jobs when Merge Succeeds

Viewed 359

I have three K8s clusters; staging, sandbox, and production. I would like to:

  1. Trigger a pipeline to build and deploy an image to staging, if a merge request to master is created
  2. Upon a successful deploy of staging, I would like the branch to be merged into master
  3. I would like to use the same image I already built in the build job before the staging deploy, to be used to deploy to sandbox and production

Something like this:

build:
  ... (stuff that builds and pushes "$CI_REGISTRY_IMAGE:$IMAGE_TAG")
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'

staging:
  ...
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'

sandbox:
  ...
  ?

production:
  ...
  ?

What I can't figure out is how to both have a successful MR at the end of the staging job and thereby have the pipeline merge the branch into master, and also then pass down whatever $CI_REGISTRY_IMAGE:$IMAGE_TAG was to continue with the jobs for the sandbox and production deploys.

1 Answers

Trigger a pipeline to build and deploy an image to staging, if a merge request to master is created

For first you can create rules like

only:
     - merge_requests
   except:
     variables:
       - $CI_MERGE_REQUEST_TARGET_BRANCH_NAME != "master"

You can run the curl command or hit API to approve the MR https://gitlab.example.com/api/v4/projects/:id/merge_requests/:merge_request_iid/approve

Reference : https://stackoverflow.com/a/58036578/5525824

Document: https://docs.gitlab.com/ee/api/merge_requests.html#accept-mr

I would like to use the same image I already built in the build job before the staging deploy, to be used to deploy to sandbox and production

You can use the TAG_NAME: $CI_COMMIT_REF_NAME passing across the stages as Environment variable

You are making it really complicated ideally you can use the TAG and make it easy to manage and deploy using the CI.

Merge when MR gets merged and create TAG and build docker images with TAG name, deploy that same TAG across environment simple.

Related