How to create a job using the REST API and cURL?

Article ID:220857567
2 minute readKnowledge base

Issue

I would like to be able to create a job remotely using the Jenkins REST API and cURL. This provides a workaround for JENKINS-12543, that doesn’t require SSH Key Authentication.

Resolution

First, create a job using the UI. This job can be used to create a base config that can be used to create new jobs.

To retrieve the job config.xml that you made via the UI, to use for creating new jobs:

curl -X GET https://example.com/job/test/config.xml -u username:API_TOKEN -o mylocalconfig.xml

Replace:

  • username:API_TOKEN with your username and password/API_Token

  • example.com with your Jenkins URL

  • test with the name of the job that you created via the UI

  • mylocalconfig.xml with the name and optionally path of this config file, which is generated locally.

You can now modify this config file locally to suit for needs as required.

Once ready, to use this config to create a new job:

curl -s -X POST 'https://example.com/createItem?name=yourJobName' -u username:API_TOKEN --data-binary @mylocalconfig.xml -H "Content-Type:text/xml"

Replace:

  • username:API_TOKEN with your username:password

  • example.com with your Jenkins URL

  • yourJobName with the name you would like to give the new job name

  • mylocalconfig.xml with the name and path to your local config file.

If the output message is an error message like

Error 403 No valid crumb was included in the request

means that the CSRF Protection is enabled in the Jenkins instance, thus the curl command requires the crumb field. In that case, try this:

CRUMB=$(curl -s 'https://example.com/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)' -u username:API_TOKEN)
curl -s -XPOST 'https://example.com/createItem?name=yourJobName' -u username:API_TOKEN --data-binary @mylocalconfig.xml -H "$CRUMB" -H "Content-Type:text/xml"
Jobs created though the REST API are subjected to migration by the RunIdMigrator on the next Jenkins startup. Please have a look at Jenkins Startup logs show RunIdMigrator logs.

See Remote Access API for more.