Created
November 28, 2023 04:20
-
-
Save JoshuaOliphant/25d3b4c92b44b35453ba3f982a6e91bb to your computer and use it in GitHub Desktop.
Download Gitlab artifacts from project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import os | |
GITLAB_TOKEN = 'YOUR_GITLAB_TOKEN' | |
GITLAB_PROJECT_ID = 'YOUR_GITLAB_PROJECT_ID' | |
PIPELINE_ID = 'PIPELINE_ID' | |
GITLAB_API_URL = f'https://gitlab.com/api/v4/projects/{GITLAB_PROJECT_ID}' | |
# Create a session for persistent headers | |
session = requests.Session() | |
session.headers.update({'PRIVATE-TOKEN': GITLAB_TOKEN}) | |
def get_pipeline_jobs(pipeline_id): | |
url = f'{GITLAB_API_URL}/pipelines/{pipeline_id}/jobs' | |
response = session.get(url) | |
response.raise_for_status() | |
return response.json() | |
def download_artifact(job): | |
job_id = job['id'] | |
job_name = job['name'] | |
artifact_url = f'{GITLAB_API_URL}/jobs/{job_id}/artifacts' | |
response = session.get(artifact_url, stream=True) | |
if response.status_code == 200: | |
artifact_path = f'artifacts/{job_name}_{job_id}.zip' | |
os.makedirs(os.path.dirname(artifact_path), exist_ok=True) | |
with open(artifact_path, 'wb') as file: | |
for chunk in response.iter_content(chunk_size=8192): | |
file.write(chunk) | |
print(f'Downloaded: {artifact_path}') | |
else: | |
print(f'No artifacts found for job {job_name} with ID {job_id}') | |
def main(): | |
jobs = get_pipeline_jobs(PIPELINE_ID) | |
for job in jobs: | |
if job['artifacts_file']: | |
download_artifact(job) | |
else: | |
print(f"No artifacts for job {job['name']} with ID {job['id']}") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment