Skip to content

Commit 3d31939

Browse files
committed
authenticate API calls on GitLab
cancel pipeline if not necessary avoid to receive notifications for a failed job
1 parent f351d38 commit 3d31939

File tree

1 file changed

+28
-8
lines changed

1 file changed

+28
-8
lines changed

ci/lib/check/run-pipeline-if-necessary.sh

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,23 @@ FUNCTIONS_FILE=${PF_SRC_DIR}/ci/lib/common/functions.sh
1212

1313
source ${FUNCTIONS_FILE}
1414

15+
# GitLab API: https://docs.gitlab.com/ee/api/
16+
1517
configure_and_check() {
1618
CI_PROJECT_ID=${CI_PROJECT_ID:-}
19+
CI_PIPELINE_ID=${CI_PIPELINE_ID:-}
1720
CI_COMMIT_REF_NAME=${CI_COMMIT_REF_NAME:-}
21+
GITLAB_API_TOKEN=${GITLAB_API_TOKEN:-}
1822

1923
COMMIT_REF_NAME_ENCODED=$(urlencode "$CI_COMMIT_REF_NAME")
2024
COMMIT_SHA=$(git rev-parse HEAD~0)
25+
26+
[ -z "${GITLAB_API_TOKEN}" ] && die "not set: GITLAB_API_TOKEN"
2127

2228
# get SHA of latest pipeline scheduled with status=succes for that branch
23-
SHA_LATEST_PIPELINE=$(curl -s "https://gitlab.com/api/v4/projects/${CI_PROJECT_ID}/pipelines?status=success&source=schedule&ref=${COMMIT_REF_NAME_ENCODED}" | jq -r '.[0].sha')
29+
SHA_LATEST_PIPELINE=$(curl --header "PRIVATE-TOKEN: ${GITLAB_API_TOKEN}" \
30+
-s "https://gitlab.com/api/v4/projects/${CI_PROJECT_ID}/pipelines?status=success&source=schedule&ref=${COMMIT_REF_NAME_ENCODED}" \
31+
| jq -r '.[0].sha')
2432

2533
RUN_PIPELINE=yes
2634

@@ -36,20 +44,32 @@ configure_and_check() {
3644
declare -p RUN_PIPELINE
3745
}
3846

39-
set_exit_code() {
47+
cancel_pipeline() {
48+
curl --request POST \
49+
--header "PRIVATE-TOKEN: ${GITLAB_API_TOKEN}" \
50+
-s "https://gitlab.com/api/v4/projects/${CI_PROJECT_ID}/pipelines/${CI_PIPELINE_ID}/cancel" \
51+
| jq -r '.status'
52+
}
53+
54+
define_next_action() {
4055
if [ "$RUN_PIPELINE" = "yes" ]; then
4156
echo "We need to run a pipeline"
4257
exit 0
4358
else
44-
# GitLab job will failed and prevent execution of next job
45-
echo "No need to run a pipeline"
46-
exit 1
59+
echo "No need to run a pipeline, cancelling pipeline"
60+
if [ $(cancel_pipeline) = "canceled" ]; then
61+
echo "Pipeline canceled"
62+
exit 0
63+
else
64+
echo "Unable to cancel pipeline"
65+
# job will failed and pipeline will be stopped
66+
exit 1
67+
fi
4768
fi
4869
}
4970

50-
5171
log_section "Configure and check"
5272
configure_and_check
5373

54-
log_section "Set exit code"
55-
set_exit_code
74+
log_section "Define next action"
75+
define_next_action

0 commit comments

Comments
 (0)