version v7.2.
For up-to-date documentation, see the
latest version.
GitLab tokens
6 minute read
Introduction
In GitLab, tokens are used to facilitate secure access to the GitLab API, manage permissions, and automate processes. Here are the different types of tokens you might encounter:
- Personal Access Tokens: These are user-specific tokens that allow you to authenticate API requests with your user account. They can be scoped to different permissions, such as read or write access to the repository.
- Project Access Tokens: These tokens are designed for automated processes within a specific project. They can be used for CI/CD pipelines, allowing services to interact with the project without exposing personal credentials.
- Group Access Tokens: These tokens grant access to all projects within a specific group. They are useful for situations where you want to manage permissions across multiple projects efficiently.
How to create a personal Access Token
Here are the steps you typically follow:
Access User Settings: Select your profile picture or avatar in the upper right corner of the page, and select Edit profile from the dropdown menu.
Navigate to Access Tokens: On the left sidebar, locate and select Access Tokens.
Fill in the Token Details:
- Name: Provide a name for your token (e.g.,
my-personal-token). - Expires at: You can set an expiration date for the token.
- Scopes: Select the appropriate scopes you want your token to have. Common scopes include:
api: Full API access.read_user: Read-only access to user profile info.read_api: Read-only access to the API.write_repository: Write access to repositories.- And others depending on what you need.
- Name: Provide a name for your token (e.g.,
Create the Token: After filling out the details, select the Create personal access token button.
Save Your Token: Once the token is created, it will be displayed on the screen. Make sure to copy it and store it securely, as you won’t be able to see it again once you leave the page.
Remember, Personal Access Tokens should be kept secure and not shared publicly, as they can grant access to your GitLab account.
If you ever need to revoke a token, follow the steps below.
Revoke a Personal Access Token
Revoking a Personal Access Token in GitLab is a simple process. Here are the steps you typically follow:
Access User Settings: Select your profile picture or avatar in the upper right corner of the page, and select Edit profile from the dropdown menu.
Navigate to Access Tokens: On the left sidebar, locate and select Access Tokens.
View Your Tokens: If there’s a section for Personal Access Tokens, you will see a list of tokens that you’ve created.
Revoke the Token: Find the token you wish to revoke and look for a button or link labeled Revoke or Delete next to it. Select this option.
Confirm Revocation: You may be prompted to confirm that you want to revoke the token. Confirm your choice.
Once you revoke a token, it will no longer work for authentication or API access, so ensure you’re revoking the correct one.
How to rotate group/project tokens
Start with creating a new personal access token like seen in the previous section with a least the
api scope.
- Navigate to Group Settings: Navigate to the group for which you want to rotate the token.
- Access Tokens: On the left sidebar, go to Settings > Access Tokens.
- Rotate: under the section for the token you want to rotate, select Rotate Icon. you wil get a warning that the old token will be invalidated.
- Save your new Token: Follow the prompts to generate a new token and update any services or scripts using the old token with the new one.
Rotate your group token programmatically
You can use the GitLab API to rotate your group token programmatically.
You should have the necessary permissions (owner) to perform this action.
Here is an example using Python and the requests library:
import requests
# Configuration
GITLAB_URL = "https://gitlab.thalesdigital.io" # Change to your GitLab instance URL
YOUR_ACCESS_TOKEN = "<your-personal-token-with-api-scope>" # Existing personal access token
GROUP_ID = <group-you-have-ownership> # The group ID your token belongs to
token_id="None"
tokens_url = f"{GITLAB_URL}/api/v4/groups/{GROUP_ID}/access_tokens"
# Headers for authentication
headers = {
"PRIVATE-TOKEN": YOUR_ACCESS_TOKEN
}
# Fetch existing access tokens
current_tokens_response = requests.get(tokens_url, headers=headers)
if current_tokens_response.status_code == 200:
print("Successfully retrieved tokens:")
tokens = current_tokens_response.json()
if tokens:
last_active_token = tokens[-1] # Get the last token in the list
token_id = last_active_token['id']
print (f"Token to rotate is : {token_id}")
else:
print("Failed to retrieve current group access tokens.")
print(f"Status Code: {current_tokens_response.status_code}")
print(f"Response: {current_tokens_response.text}")
# If a token was not found, end processing.
if token_id == "None":
print("No active tokens found to rotate.")
exit()
# API endpoint to rotate the group access token
rotate_token_url = f"{GITLAB_URL}/api/v4/groups/{GROUP_ID}/access_tokens/{token_id}/rotate"
# Try to rotate the token
rotate_response = requests.post(rotate_token_url,headers=headers)
# Check if the token was rotated successfully
if rotate_response.status_code == 200:
new_id = rotate_response.json().get("id")
new_token = rotate_response.json().get("token")
print("New group access token created successfully!")
print(f"Response - your new token id : {new_id}")
else:
print("Failed to rotate the group access token.")
print(f"Status Code: {rotate_response.status_code}")
print(f"Response: {rotate_response.text}")
Here an example using curl :
- Fetch all available tokens at group level:
curl --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.thalesdigital.io/api/v4/groups/<group_id>/access_tokens"
The response will be a JSON response containing details of all tokens, including their IDs, names, and expiration dates.
- Parse the JSON response to extract the active token ID.
- Once your get the token id from JSON response, you can rotate this token :
## rotate one token
token_rotation_response=$( curl --request POST \
--header "PRIVATE-TOKEN: <your_access_token>" \
--url "https://gitlab.thalesdigital.io/api/v4/groups/<group_id>/access_tokens/<token_id>/rotate" )
- The response will include the new token details. You can extract the new token using a tool like
jq:
new_rotate_token_id=$(echo $token_rotation_response | jq -r '.[0].id')
- Please visit official GitLab documentation on group token rotation
- Please visit official GitLab documentation on personal token rotation
- Please visit official GitLab documentation on project token rotation
Project Access Tokens
Navigate to Your Project Settings:
- Go to the specific project in GitLab.
- In the left sidebar, select Settings > Access Tokens.
Create a New Project Access Token:
- Select Add New Token.
- Fill in the
Token nameandToken description. - Set an
Expiration datefor the token. - Select a
rolefrom the list - Select the
Scopesrequired for the token (e.g.,api,read_repository,write_repository, etc.). - Select Create project access token.
- Copy the generated token and store it securely, as it will only be shown once.
Group Access Tokens
Navigate to Your Group Settings:
- Go to the specific group in GitLab.
- In the left sidebar, select Settings > Access Tokens.
Create a New Group Access Token:
- Select Add New Token.
- Fill in the
Token nameandToken description. - Set an
Expiration datefor the token. - Select a
rolefrom the list - Select the
Scopesrequired for the token (e.g.,api,read_repository,write_repository, etc.). - Click Create group access token.
- Copy the generated token and store it securely, as it will only be shown once.
Deploy Tokens
Navigate to Your Project Settings:
- Go to the specific project in GitLab.
- In the left sidebar, select Settings > Repository.
Create a New Deploy Token:
- Scroll down to Deploy Tokens and select Add deploy token.
- Fill in the
Nameand optionnalyUsername. - Set an
Expiration datefor the token. - Select the Scopes required for the token (
read_repository,read_registry, etc.). - Select Create deploy token.
- Copy the generated token and store it securely, as it will only be shown once.
CI_JOB_TOKEN
- Automatic Generation: The
CI_JOB_TOKENis automatically generated for each job in the CI pipeline and can be accessed via environment variables within the job script. - Usage: Use
CI_JOB_TOKENwithin your.gitlab-ci.ymlfile to authenticate CI/CD jobs to interact with limited GitLab API endpoints.