Skip to content

Instantly share code, notes, and snippets.

@justAsascha
Last active February 2, 2023 21:25
Show Gist options
  • Save justAsascha/95e133ba30a9f789362e12c70149017c to your computer and use it in GitHub Desktop.
Save justAsascha/95e133ba30a9f789362e12c70149017c to your computer and use it in GitHub Desktop.
Validates gitlab ci templates
#############################
# Example usage (gitlab ci) #
#############################
# This script validates gitlab-ci scripts against the gitlab ci lint api.
# Requirments: you need to generate a Project Access Tokens and pass it to the CI as env variable.
# see: https://docs.gitlab.com/ee/user/project/settings/project_access_tokens.html
# Usage: python gitlabci-validate.py [PROJECT_ACCESS_TOKEN] [CI_TEMPLATE_PATH]
# Python packages: requests pyyaml json
#default:
# image: python:3.10
#
# before_script:
# - pip install requests pyyaml
# - echo "CI_COMMIT_REF_NAME" $CI_COMMIT_REF_NAME
#
#stages:
# - validate
#sam template:
# stage: validate
# script:
# - python validate-ci.py $PROJECT_ACCESS_TOKEN 'examples/sam.yml'
import requests
import json
import yaml
import sys
# reading arguments
GITLAB_TOKEN = sys.argv[1]
CI_TEMPLATE = sys.argv[2]
GITLAB_API = "https://gitlab.com/api/v4/ci/lint"
HEADERS = {
'PRIVATE-TOKEN': GITLAB_TOKEN,
}
with open(CI_TEMPLATE, 'r') as template_file:
yaml_template = yaml.safe_load(template_file)
# here you can manipulate your ci template
# example: overwrite branch:
#if GIT_REF:
# yaml_template['include'][0]['ref'] = 'feat/helloworld"
parsed_template = json.dumps(yaml_template)
body = {
"dry_run": True,
"content": parsed_template
}
result = requests.post(GITLAB_API, headers=HEADERS, data=body)
response = result.json()
if result.status_code != 200:
print(f"HTTP error {result.status_code}")
exit(1)
if response['status'] != 'valid':
print("Validation errors:")
print(*response['errors'], sep = "\n")
exit(1)
print("CI Template is valid.")
exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment