Trigger Jenkins job from Laravel via Guzzle Request

To trigger a Jenkins job from a Laravel application using Guzzle, you can use the Jenkins API endpoint to build a job. Follow these steps:

Create Jenkins Token

In Jenkins, click on your User Name from Top Right Navbar, inside that page go to "Configure". There you will see section "API Token". Click on "Add new token" and create token.

Copy the generated token and save it for future use.

Enable Trigger for Jenkins Job

Open your Job in Jenkins which you want to trigger.
On that page under Build Triggers section, enable checkbox Trigger builds remotely and paste you token name.

Once done save the Jenkins Job.

Install Guzzle in Laravel Project

If you haven't already installed Guzzle, do so using Composer:

composer require guzzlehttp/guzzle

Use Guzzle to Trigger Jenkins Job

Here is an example of how you can trigger a Jenkins job using Guzzle in a Laravel controller or wherever you need it:

<?php
namespace App\Http\Controllers;

use GuzzleHttp\Client;

class JenkinsController extends Controller
{
    public function triggerJob()
    {
        $JENKINS_USERNAME = 'JENKINS_USERNAME';
        $JENKINS_TOKEN_NAME = 'JENKINS_TOKEN_NAME';
        $JENKINS_TOKEN = 'JENKINS_TOKEN';
        $client = new Client();
        $response = $client->post("http://YOUR_JENKINS_URL/job/JOB_NAME/build?token=$JENKINS_TOKEN_NAME&cause=deploy-app", [
            'auth' => [$JENKINS_USERNAME, $JENKINS_TOKEN],
        ]);

        // Returns the HTTP status code
        return $response->getStatusCode();
    }
}

Make sure to replace the placeholders like YOUR_JENKINS_URL, JOB_NAME, JENKINS_USERNAME, JENKINS_TOKEN_NAME and JENKINS_TOKEN with your actual Jenkins server details.

Job Trigger

Now, you can access the triggerJob method from your routes and run Jenkins Job.

Remember to secure your Laravel application and Jenkins instance, especially if it's exposed to the internet. This might include using HTTPS, authentication, and access control measures.

Also, ensure that your Laravel application has the necessary permissions to make external HTTP requests. If your application is running in a Docker container, make sure it has network access to reach the Jenkins server.

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.