Search code examples
gitlabintegrationartifactoryjfrog-cli

How to delete artifacts automatically in JFrog while deleting specific branch on Gitlab?


I'm in need of integration of JFrog with Gitlab. My main goal is to delete all artifacts in JFrog automatically after specific branch is deleted. I've read about webhooks, but I am not certain how to use them effectively. What is the best solution for this kind of problem?


Solution

  • You can delete Artifactory artifacts using the JFrog CLI:

    jfrog rt del --quiet --recursive "my-repo/path/to/branch/artifacts"
    

    There are a few ways to trigger this command when a branch is deleted in GitLab:

    1. Trigger an on_stop_action when you stop a GitLab environment
    2. Configure a GitLab webhook on branch delete

    GitLab Stop Environment

    • Each branch you create will be assigned a unique GitLab Environment.
    • When the branch is deleted, the corresponding GitLab environment will automatically be stopped.
    • This will trigger an on_stop_action, which in turn can trigger a pipeline job to call the JFrog CLI.
    • You can also stop the environment manually in the GitLab web UI or using the GitLab API. If you don't want to delete artifacts in these scenarios, add rules to the stop job.
    • See Stop an environment when a branch is deleted for more info.

    The gitlab-ci.yml jobs will look something like this (assumes JFrog CLI has already been installed in your GitLab runner images):

    deploy_artifacts:
      stage: deploy
      script:
        - echo "Deploy artifacts to JFrog Artifactory"
      environment:
        name: project/$CI_COMMIT_REF_SLUG
        url: <optionally enter artifact URL here>
        on_stop: delete_artifacts
      rules:
        - if: $CI_MERGE_REQUEST_ID
    
    delete_artifacts:
      stage: deploy
      script:
        - jfrog rt del --quiet --recursive "my-repo/path/to/branch/artifacts"
      environment:
        name: project/$CI_COMMIT_REF_SLUG
        action: stop
      rules:
        - if: $CI_MERGE_REQUEST_ID
          when: manual
    

    If you can’t use pipelines for merge requests, set the GIT_STRATEGY to none in the delete_artifacts job. Then the runner doesn’t try to check out the code after the branch is deleted.

    GitLab Webhooks

    • GitLab can call a webhook URL with a POST request when certain events occur
    • To trigger a GitLab webhook event when a branch is deleted, use the basic push event
    • Some fields in the push event POST request are unique to deleting a branch. See this GitLab issue for more info.
    • You'll need to setup a webhook receiver to process the webhook POST requests

    If you haven't setup custom webhooks before, it can get a bit complicated. In that case, I would recommend using GitLab environments instead.