0

How can I set up global environment variables in GitLab that are not project-specific, but apply to all projects? Classic use cases are deployment keys, docker registry credentials and connect proxy information.

People have been asking about it for three years, as you can see in the following link. Unfortunately the issue has been closed.

https://gitlab.com/gitlab-org/gitlab-foss/issues/3897

uav
  • 494
  • 3
  • 16

1 Answers1

0

In the meantime, I've helped myself.

Setup

sudo vi gitlab_global_env.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# sudo pip3 install requests

import os
import requests
import sys
import time

gitlab_url = 'https://gitlab.example.com/api/v4/'

# https://gitlab.example.com/profile/personal_access_tokens
headers = {'PRIVATE-TOKEN': '***TODO***'}

lol = {
    'HTTP_PROXY': 'http://corporateproxy:8123',
    'HTTPS_PROXY': 'http://corporateproxy:8123',
    'NO_PROXY': '127.0.0.1,localhost,.local'  # max. 1024 chars!
}

r = requests.get(f'{gitlab_url}projects?per_page=100', headers=headers)  # max. 100 projects without paging!
projects = r.json()

for elt in projects:
    pid = elt['id']
    path_with_namespace = elt['path_with_namespace']
    visibility = elt['visibility']
    print(f'pid: {pid} -- path_with_namespace: {path_with_namespace} -- visibility: {visibility}')
    for k, v in lol.items():
        # https://docs.gitlab.com/ce/api/project_level_variables.html
        # https://docs.gitlab.com/ee/api/project_level_variables.html
        # Create:
        r = requests.post(f'{gitlab_url}/projects/{pid}/variables', data={'key': k, 'value': v}, headers=headers)
        create = r.json()
        if create.get('message'):
            # print(create)
            # Update:
            r = requests.put(f'{gitlab_url}/projects/{pid}/variables/{k}', data={'value': v}, headers=headers)
            update = r.json()
            if update.get('message'):
                print(update)

Run

sudo python3 gitlab_global_env.py

Example output

pid: 1 -- path_with_namespace: group/repo -- visibility: private

Check

Project, Settings, CI / CD, Variables, Collapse.

enter image description here

Tested with Python 3.6.8

uav
  • 494
  • 3
  • 16