How can a Jenkins user authentication details be "passed" to a script which uses Jenkins API to create jobs?
I have a script that delete and re-create jobs through curl HTTP-calls and I want to get rid of any hard-coded "username:password".
E.g. curl -X POST $url --user username:password
Considerations:
Jenkins CLI (probably not an option). One should be able to achieve the same with the CLI as with Jenkins API (creating jobs etc) but as far as I understand Jenkins CLI is not a good alternative for me since jobs created with will only appear in Jenkins after restarting or a "Reload Configuration from Disk", and that would cancel any other running jobs.
API token. Can't find out how to get the user token and then pass it as a parameter to the script, but that may be a solution..
Solution 1:
Try this way: (for example delete the job)
curl --silent --show-error http://<username>:<api-token>@<jenkins-server>/job/<job-name>/doDelete
The api-token can be obtained from http://<jenkins-server>/user/<username>/configure
.
Solution 2:
This worked for me:
curl -u $username:$api_token -FSubmit=Build 'http://<jenkins-server>/job/<job-name>/buildWithParameters?environment='
API token can be obtained from Jenkins user configuration.
Solution 3:
With Jenkins CLI you do not have to reload everything - you just can load the job (update-job command). You can't use tokens with CLI, AFAIK - you have to use password or password file.
Token name for user can be obtained via
http://<jenkins-server>/user/<username>/configure
- push on 'Show API token' button.Here's a link on how to use API tokens (it uses
wget
, butcurl
is very similar).
Solution 4:
I needed to explicitly add POST in the CURL command:
curl -X POST http://<user>:<token>@<server>/safeRestart
I also have the SafeRestart Plugin installed, in case that makes a difference.
Solution 5:
If you want to write a script to automate creation of jobs using the Jenkins API, you can use one of the API clients to do that. A ruby client for Jenkins is available at https://github.com/arangamani/jenkins_api_client
gem install jenkins_api_client
require "rubygems"
require "jenkins_api_client"
# Initialize the client by passing in the server information
# and credentials to communicate with the server
client = JenkinsApi::Client.new(
:server_ip => "127.0.0.1",
:username => "awesomeuser",
:password => "awesomepassword"
)
# The following block will create 10 jobs in Jenkins
# test_job_0, test_job_1, test_job_2, ...
10.times do |num|
client.job.create_freestyle(:name => "test_job_#{num}")
end
# The jobs in Jenkins can be listed using
client.job.list_all
The API client can be used to perform a lot of operations.