Begin destroy/Cleanup after merge request is closed/merged

56 Views Asked by At

I'm trying to write code in my gitblab-ci.yml which builds our instance when we create a merge request and deletes it once it is merged. This is what I have written so far;

stages:
  - build
  - test
  - preview
  - deploy
  - cleanup

include:
  - local: '/jobs/node-micro-install.gitlab-ci.yml'
  - local: '/jobs/node-micro-build.gitlab-ci.yml'
  - local: '/jobs/node-micro-lint.gitlab-ci.yml'
  - local: '/jobs/node-micro-format.gitlab-ci.yml'
  - local: '/jobs/node-micro-tests.gitlab-ci.yml'
  - local: '/jobs/node-micro-nexus_iq_scan.gitlab-ci.yml'
  - local: '/jobs/node-micro-sonarqube.gitlab-ci.yml'
  - local: '/jobs/node-micro-preview.gitlab-ci.yml'

workflow:
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request"'
      changes:
        - '.gitlab-ci.yml'

dev_preview:
  extends: .preview
  stage: preview
  variables:
    BT_AWS_ASSUME_ROLE_ARN: arn:aws:iam::${AWS_ACCOUNT_ID_DEV}:role/GitlabCICDRunnerPulumiAdminRole

dev_deploy:
  extends: .preview
  stage: deploy
  when: on_success
  script:
    - | 
      if [[ "$CI_COMMIT_REF_NAME" =~ ^(feat|fix) ]]; then
        # Deploy your instance here using appropriate commands or scripts
        echo "Deploying instance for branch $CI_COMMIT_REF_NAME"
        # Deploy using pulumi
        Pulumi up --stack dev # Replace 'dev' with your actual stack name
      fi
  needs: ["dev_preview"]

dev_cleanup:
  stage: cleanup
  script:
    - |
      if [[ "$CI_PIPELINE_SOURCE" == "push" && "$CI_COMMIT_REF_NAME" == "$CI_DEFAULT_BRANCH" ]]; then
        if [[ "$CI_COMMIT_SHA" == "$CI_MERGE_SHA" ]]; then
          # Destroy or cleanup your instance here using appropriate commands or scripts
          echo "Cleaning up instance for branch $CI_COMMIT_REF_NAME"
          # Destroy the instance
          Pulumi destroy --stack dev # Replace 'dev' with your actual stack name
        fi
      fi
  rules:
    - changes:
        - "$CI_DEFAULT_BRANCH"
  needs:
    - job: dev_deploy

When it is triggered and merged after it doesn't initiate the cleanup. Even in the CI/CD pipeline, it doesn't show the cleanup as part of a job CI/CD pipeluine. How can I properly execute this task?

0

There are 0 best solutions below