Trigger Jenkins jobs via API and curl

April 23, 2020 - Last updated: July 23, 2020

After upgrade Jenkins, we face an issue (Error 403 No valid crumb was included in the request). We have a few solution they need to trigger Jenkins's job externally via curl command before they start working. For trigger jobs we use a service account in Jenkins.

Requirements

  • User in Jenkins.
  • User API Token.
  • Crumb Token for CSRF Protection
  • Jenkins version > 2.222.1

Resolution

Generate an API token for the user.

Sidebar > People > {USERNAME} > Configure > API Token > Add new Token

Get the Crumb token.

USERNAME="<CHANGE_FOR_YOUR_USERNAME>"
API_TOKEN="<CHANGE_FOR_THE_API_TOKEN_FOR_THE_USER>"

CRUMB=`curl -s -u "${USERNAME}:${API_TOKEN}" 'https://myjenkins.com/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)'`

Trigger the job.

curl -s -X POST -u "${USERNAME}:${API_TOKEN}" \
    -H "${CRUMB}" \
    "https://myjenkins.com/job/job-name/build"

Issues

HTTP/1.1 403 Forbidden

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 403 No valid crumb was included in the request</title>
</head>
<body><h2>HTTP ERROR 403 No valid crumb was included in the request</h2>
<table>
<tr><th>STATUS:</th><td>403</td></tr>
<tr><th>MESSAGE:</th><td>No valid crumb was included in the request</td></tr>
<tr><th>SERVLET:</th><td>Stapler</td></tr>
</table>
<hr><a href="http://eclipse.org/jetty">Powered by Jetty:// 9.4.27.v20200227</a><hr/>

</body>
</html>

Related posts