Skip to content

Instantly share code, notes, and snippets.

@jbanety
Created June 2, 2024 19:09
Show Gist options
  • Save jbanety/dac1cb8852b6a2c46623df47c4f40517 to your computer and use it in GitHub Desktop.
Save jbanety/dac1cb8852b6a2c46623df47c4f40517 to your computer and use it in GitHub Desktop.
This Bash script exports all CI/CD variables from your GitLab instance, including instance-level, group-level, and project-level variables, and saves them into a backup file.
#!/bin/bash
# Replace with your personal GitLab access token
PRIVATE_TOKEN="YOUR_PRIVATE_TOKEN"
# Replace with the URL of your GitLab instance
GITLAB_URL="https://gitlab.example.com"
# Backup file
BACKUP_FILE="gitlab_ci_cd_variables_backup.txt"
# Function to export instance-level CI/CD variables
export_instance_variables() {
echo "Instance-level CI/CD variables" >> "$BACKUP_FILE"
curl --silent --header "PRIVATE-TOKEN: $PRIVATE_TOKEN" "$GITLAB_URL/api/v4/admin/ci/variables" | jq -r '.[] | "\(.key) = \(.value)"' >> "$BACKUP_FILE"
echo "" >> "$BACKUP_FILE"
}
# Function to export group-level CI/CD variables
export_group_variables() {
group_info=$(curl --silent --header "PRIVATE-TOKEN: $PRIVATE_TOKEN" "$GITLAB_URL/api/v4/groups" | jq -c '.[] | {id, full_path}')
echo "$group_info" | while IFS= read -r group; do
group_id=$(echo $group | jq -r '.id')
group_path=$(echo $group | jq -r '.full_path')
echo "Group-level CI/CD variables for group $group_path (ID $group_id)" >> "$BACKUP_FILE"
curl --silent --header "PRIVATE-TOKEN: $PRIVATE_TOKEN" "$GITLAB_URL/api/v4/groups/$group_id/variables" | jq -r '.[] | "\(.key) = \(.value)"' >> "$BACKUP_FILE"
echo "" >> "$BACKUP_FILE"
done
}
# Function to export project-level CI/CD variables
export_project_variables() {
project_info=$(curl --silent --header "PRIVATE-TOKEN: $PRIVATE_TOKEN" "$GITLAB_URL/api/v4/projects?membership=true" | jq -c '.[] | {id, path_with_namespace}')
echo "$project_info" | while IFS= read -r project; do
project_id=$(echo $project | jq -r '.id')
project_path=$(echo $project | jq -r '.path_with_namespace')
echo "Project-level CI/CD variables for project $project_path (ID $project_id)" >> "$BACKUP_FILE"
curl --silent --header "PRIVATE-TOKEN: $PRIVATE_TOKEN" "$GITLAB_URL/api/v4/projects/$project_id/variables" | jq -r '.[] | "\(.key) = \(.value)"' >> "$BACKUP_FILE"
echo "" >> "$BACKUP_FILE"
done
}
# Initialize the backup file
echo "GitLab CI/CD Variables Backup" > "$BACKUP_FILE"
echo "Backup Date: $(date)" >> "$BACKUP_FILE"
echo "" >> "$BACKUP_FILE"
# Call functions to export variables
export_instance_variables
export_group_variables
export_project_variables
echo "Backup completed and saved to $BACKUP_FILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment