Turning a git branch name into a valid docker image tag
When using GitLab CI, you can use a predefined variable CI_COMMIT_REF_SLUG
, description:
$CI_COMMIT_REF_NAME
lowercased, shortened to 63 bytes, and with everything except0-9
anda-z
replaced with-
. No leading / trailing -. Use in URLs, host names and domain names.
Source
Docker tag does not allow most of the special character except -,_,.
.
A tag name must be valid ASCII and may contain lowercase and uppercase letters, digits, underscores, periods and dashes. A tag name may not start with a period or a dash and may contain a maximum of 128 characters.
docker valid image tags
So you can replace all special character with -
. in your Branch name.
docker build . -t image_name:$(git rev-parse --abbrev-ref HEAD | sed 's/[^a-zA-Z0-9]/-/g')
So the following branch will become
fix/bug#123 -> fix-bug-123
pr@123 -> pr-123
You can replace -
with underscores, periods and dashes
#to use `_`
sed 's/[^a-zA-Z0-9]/_/g'