I need to automate the triggering of a specific Jenkins job from an external server using a shell script. I'm looking for the correct syntax to use with curl to handle authentication via API tokens and how to pass multiple build parameters. Also, are there specific headers or "crumbs" required for CSRF protection that I need to include to ensure the script doesn't fail with a 403 Forbidden error?
3 answers
The most common way to trigger a Jenkins job via shell is using curl with the REST API. First, you should use an API token instead of your password for security. The basic syntax is curl -u "user:token" -X POST "http://jenkins-url/job/job-name/build". If your job requires parameters, use the buildWithParameters endpoint and pass them using the --data flag: curl -u "user:token" -X POST "http://jenkins-url/job/job-name/buildWithParameters" --data "PARAM1=value1" --data "PARAM2=value2". To handle CSRF protection, you must first fetch a "crumb" by calling the /crumbIssuer/api/xml endpoint and then pass that crumb in your final POST request header using -H "Jenkins-Crumb: <VALUE>". This ensures your request is authenticated and authorized.
Does your Jenkins instance have the "Trigger builds remotely" option enabled in the job configuration, and have you defined a specific authentication token there that is separate from your user API token?
You can also use the Jenkins CLI jar file. It's often easier for complex jobs as it handles the authentication and waiting for build completion much more gracefully than raw curl.
I agree with Jennifer. The CLI command java -jar jenkins-cli.jar build
I actually tried using the job-specific token initially, but I found that if the global security settings require "Prevent Cross Site Request Forgery exploits," the job-level token still requires a Crumb header from the user. I've switched to using the user-level API token combined with the crumb fetch logic in my script, and it seems to be much more consistent across different environments.