GitLab allows generating multiple kinds of tokens like Personal Access Tokens (PATs), Pipeline Trigger Tokens (PTTs), and Runner Registration Tokens (RRTs). Leaking a GitLab token in source code can cause severe security issues as it can give unauthorized access to GitLab resources, which can result in a data breach and financial loss due to unauthorized utilization of GitLab resources. If a token has been leaked, you can revoke the token to mitigate the vulnerability.
It is recommended to use environment variables to store the token. This ensures that the token is not hardcoded in the source code and is kept separate from the codebase. Using environment variables also makes it easier to manage the token as it can be updated without modifying the source code. Additionally, it is recommended that access to the token is restricted to only those who need it, by using GitLab's access control features.
import gitlab
gl = gitlab.Gitlab('https://gitlab.example.com', private_token='my_secret_token')
project = gl.projects.get('my_project_id')
import gitlab
import os
gl = gitlab.Gitlab('https://gitlab.example.com', private_token=os.getenv('GITLAB_TOKEN'))
project = gl.projects.get('my_project_id')