Sunday, September 10, 2017

Jenkins: Trigger build remotely via script using Authentication Token

Powershell:

$acctname = "admin"
$password = "password"
$server = "localhost"
$port = "8080"
$jobName = "test02"
$jobToken = "test02_authentication_token"
$params = @{uri = "http://${server}:${port}/job/${jobName}/build?token=${jobToken}";
            Method = 'Get';
            Headers = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$(${acctname}):$(${password})"));}}
Invoke-RestMethod @params





Python:

import requests

api_proto = 'http'
api_url = 'localhost'
api_port = '8080'
api_job = 'test02'
api_token = 'test02_authentication_token'
api_user = 'admin'
api_pass = 'password'

api_resp = requests.get(api_proto + '://' + api_user + ':' + api_pass + '@' + api_url + ':' + api_port + '/job/' + api_job + '/build?token=' + api_token)
if api_resp.status_code == 201 :
    print(api_resp)
else:
    print('could not trigger job: ' + api_job)



Perl:

use strict;
use warnings;
use autodie;
use REST::Client;
use MIME::Base64;

my $api_proto = 'http';            #HTTP/HTTPS
my $api_url = 'localhost';        #Server IP
my $api_port = '8080';            #Port number
my $api_job = 'test02';            #Jenkins job name
my $api_token = 'test02_authentication_token';        #Job remote trigger authentication token
my $api_user = 'admin';            #Jenkins account username
my $api_pass = 'password';        #Jenkins account password

my $client = REST::Client->new();
$client->addHeader('Authorization', 'Basic '.encode_base64($api_user . ':' . $api_pass));
$client->GET($api_proto.'://'.$api_url.':'.$api_port.'/job/'.$api_job.'/build?token='.$api_token);

print $client->responseContent();
print $client->responseCode();



PHP:

<?php

$api_url = 'localhost';
$api_port = '8080';
$api_user = 'admin';
$api_pass = 'password';
$api_job = 'test02';
$api_token = 'test02_authentication_token';

$domain = 'http://'.$api_user.':'.$api_pass.'@'.$api_url.':'.$api_port.'/job/'.$api_job.'/build?token='.$api_token;

function get_http_response_code($domain) {
  $headers = get_headers($domain);
  return substr($headers[0], 9, 3);
}

$get_http_response_code = get_http_response_code($domain);

if ( $get_http_response_code == 201 ) {
  echo "OKAY! \n ".$api_job." was triggered successfully...";
} else {
  echo "Nokay! \n Something went wrong.. please try again!!";
}

?>



CURL/WGET: https://wiki.jenkins.io/display/JENKINS/Remote+access+API

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.