On a Gitlab CI/CD pipeline, how to list, create, and delete tags.
Preliminaries
This assumes that you have a Gitlab project with a Docker linux container with curl and jq installed.
Create a Repository Access Token
Access token is needed to give permission to access the Gitlab api.
Navigate to your project then go to the sidebar -> Settings -> Access Tokens.
Token name is "tag". Select scope check "api" and leave the rest unchecked. Then click project access token.
Be sure to save the token locally as once it disappears, you can not get it back again and need to create a new one.
Make a new Gitlab variable called GITLAB_TOKEN.
List Tags
#!/bin/bash
# list-tags.sh
# List all Gitlab tags for a given project.
# $CI_PROJECT_ID is a Gitlab pre-defined variable
# $GITLAB_TOKEN is a project access token that needs to be
# a defined CI/CD variable.
GITLAB_API_URL="https://gitlab.com/api/v4/projects/${CI_PROJECT_ID}"
curl -k --header "PRIVATE-TOKEN: $GITLAB_TOKEN" "${GITLAB_API_URL}/repository/tags"
Create Tag
#!/bin/bash
# create-tag.sh
# $CI_PROJECT_ID is a Gitlab pre-defined variable
# $GITLAB_TOKEN is a project access token that needs to be
# a defined CI/CD variable.
# TAG_NAME needs to be defined as a variable in the yaml.
GITLAB_API_URL="https://gitlab.com/api/v4/projects/${CI_PROJECT_ID}"
curl -k --request POST --header "PRIVATE-TOKEN: $GITLAB_TOKEN" $GITLAB_API_URL/repository/tags?tag_name=$TAG_NAME\&ref=$CI_COMMIT_SHA
Adding Code to Yaml
stages:
- deploy
tag:
stage: deploy
image: curl/curl-docker
variables:
# Make TAG_NAME a more meaningful variable
TAG_NAME: $CI_COMMIT_SHA
script:
# Create a Tag
- bash tag.sh
Top comments (0)