Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#!/bin/bash
# Uage helper
usage() {
echo "Usage: $0 [-c config_file] [-u gitlab_url] [-p project_id] [-g group_id] [-t private_token] [-r runner_type] [-d description] [-T tag_list]"
echo "Runner types: project | group | shared"
exit 1
}
# Default config file path (if any)
CONFIG_FILE="./config.env"
# Manually parse -c <file> early, remove from args
for i in "$@"; do
if [[ "$i" == "-c" ]]; then
CONFIG_FILE="$2"
shift 2
break
fi
done
# Load from config file (if exists)
if [ -f "$CONFIG_FILE" ]; then
# Load configuration values
echo "Loading config from $CONFIG_FILE..."
source "$CONFIG_FILE"
else
echo "Warning: Configuration file $CONFIG_FILE not found. Using default values or CLI arguments."
fi
# Parse command-line arguments to override config file values
OPTIND=1
while getopts "u:p:g:t:r:d:T:c:" opt; do
case $opt in
u) GITLAB_URL="$OPTARG" ;;
p) PROJECT_ID="$OPTARG" ;;
g) GROUP_ID="$OPTARG" ;;
t) PRIVATE_TOKEN="$OPTARG" ;;
r) RUNNER_TYPE="$OPTARG" ;;
d) DESCRIPTION="$OPTARG" ;;
T) TAG_LIST="$OPTARG" ;;
*) usage ;;
esac
done
# Validate required parameters
if [ -z "$GITLAB_URL" ] || [ -z "$RUNNER_TYPE" ] || [ -z "$PRIVATE_TOKEN" ]; then
echo "Error: Missing required parameters."
usage
fi
# Set default description if not provided
DESCRIPTION=${DESCRIPTION:-"Automated Runner"}
TAG_LIST=${TAG_LIST:-"build,deploy"}
# Define API endpoint and additional data based on runner type
case "$RUNNER_TYPE" in
project)
if [ -z "$PROJECT_ID" ]; then
echo "Error: PROJECT_ID is required for project runners."
exit 1
fi
EXTRA_DATA="--data runner_type=project_type --data project_id=$PROJECT_ID"
;;
group)
if [ -z "$GROUP_ID" ]; then
echo "Error: GROUP_ID is required for group runners."
exit 1
fi
EXTRA_DATA="--data runner_type=group_type --data group_id=$GROUP_ID"
;;
shared)
EXTRA_DATA="--data runner_type=instance_type"
;;
*)
echo "Error: Invalid runner type. Choose from 'project', 'group', or 'shared'."
usage
;;
esac
# Create GitLab runner config
echo "Creating GitLab runner config..."
RESPONSE=$(curl --silent --request POST --url "$GITLAB_URL/api/v4/user/runners" \
--header "PRIVATE-TOKEN: $PRIVATE_TOKEN" \
--data "description=$DESCRIPTION" \
--data "tag_list=$TAG_LIST" \
$EXTRA_DATA)
# Extract token and id from the response
RUNNER_TOKEN=$(echo $RESPONSE | jq -r '.token')
RUNNER_ID=$(echo "$RESPONSE" | jq -r '.id')
# Check if the runner creation was successful
if [ -z "$RUNNER_TOKEN" ]; then
echo "Failed to create runner on GitLab!"
exit 1
fi
echo "Runner created successfully. Check the token in file .gl-auth-token-<runner_id>"
echo $RUNNER_TOKEN 2>&1 | tee ~/.gl-auth-token-$RUNNER_ID > /dev/null