# Trigger jobs with a simple webhook

Trigger jobs with a simple webhook
==================================

If you use customized tools to create build artifacts, you can trigger jobs when a new version of a build artifact is ready with a custom HTTP call. First, you need to create a webhook on the operations center. Then, enable notifications on both the operations center and the controller. Finally, create a job on the controller that is triggered when this webhook is called.

This tutorial steps you through each of these.

[](#_prerequisites)Prerequisites
--------------------------------

The installation of the following plugins on each CloudBees CI instance:

*   [Notification API plugin](/plugins/ci/notification-api) (required): responsible for sending the messages across teams and jobs.
    
*   [Pipeline Event Step plugin](/plugins/ci/pipeline-event-step) (required): provides a Pipeline step to add a new event publisher or trigger.
    
*   [Operations Center Notification plugin](/plugins/ci/operations-center-notification) (optional): provides the router to transfer the messages across different teams, and it’s required if you want to implement cross-team collaboration. It is still possible to use the cross-team-collaboration feature without this plugin, by using the local-only mode which allows you to trigger events across different jobs inside the same team.
    

[](#_configure_a_simple_webhook_on_the_operations_center)Configure a simple webhook on the operations center
------------------------------------------------------------------------------------------------------------

To configure a simple webhook on the operations center:

1.  Select in the upper-right corner to navigate to the **Manage Jenkins** page.
    
2.  Select **Manage Notification Webhook HTTP Endpoints**.
    
    ![Manage Notification Webhook HTTP Endpoints menu item](_images/endpoint-menu.1587d2b.png)
    
    Figure 1. Manage Notification Webhook HTTP Endpoints menu item
    
3.  Select **Create a new Endpoint**.
    
4.  Enter a **Webhook Name**.
    
5.  Select **Custom JSON Webhook** as the Webhook Message Format.
    
6.  Select the **Define a list of IP addresses that are allowed to send events to this endpoint** checkbox and enter a list of IPv4 and IPv6 addresses.
    
    ![Create a new Endpoint form](_images/create-new-endpoint.fa23897.png)
    
    Figure 2. Create a new Endpoint form
    
    This use case is minimal; it works with an IP filtered endpoint. For more complex uses, see [Enable external notification events with external HTTP endpoints](/docs/cloudbees-ci/latest/pipelines/external-http-endpoints).
    
    If you do not enter an IPv4 or IPv6 address, all hosts will be denied access.
    
7.  Select **Save Webhook**.
    
    ![List of created webhooks](_images/webhook.d59bbbe.png)
    
    Figure 3. List of created webhooks
    
8.  Test the endpoint with cURL or an equivalent tool, by checking the “Last Event” and “Last Status” on the Webhook management screen.
    

    curl -vvv \
        --data '{"my_source": "homemade", "application": "real-fact", "version": "1.3",
                "fact": { "id": 7368975833,"content": "Ada Lovelace was the first programmer, ever." }}' \
        --header "Content-Type:application/json" \
        -XPOST /http://localhost:8400/webhooks/XoLZfgK/

The top level attribute `source` is a reserved field, and may be overwritten by Jenkins when processing webhook events.

Now you need a job on a controller that is triggered when this webhook is called, but first you must enable notifications on both operations center and your controller so the job can be triggered with the incoming notifications.

[](#_enable_notifications_on_both_operations_center_and_the_controller)Enable notifications on both operations center and the controller
----------------------------------------------------------------------------------------------------------------------------------------

To enable notifications on both the operations center and your controller:

1.  Select in the upper-right corner to navigate to the **Manage Jenkins** page.
    
2.  Select **Configure Notification**.
    
3.  Select the **Enabled checkbox**.
    
4.  Select **operations center Messaging** as the Notification Router Implementation.
    
    ![Enable notifications on the Notification Configuration page](_images/enable-notification.235e5bb.png)
    
    Figure 4. Enable notifications on the Notification Configuration page
    
5.  Select **Save**.
    

[](#_create_a_pipeline_job_that_is_triggered_by_a_webhook)Create a pipeline job that is triggered by a webhook
--------------------------------------------------------------------------------------------------------------

Then create a pipeline job on the controller and use the following script in your pipeline:

    pipeline {
    	agent none
    	triggers {
        		eventTrigger jmespathQuery("source=='homemade'")
    		}
    	stages {
        	stage('First stage') {
            	steps {
                	script {
                    	echo "Build triggered by:" + currentBuild.getBuildCauses()[0].toString()
                    	def cause = currentBuild.getBuildCauses()[0];
                   // We check that the job is triggered by event, to avoid NullPointerException when using the json content.
                    	if ( cause._class.contains("EventTriggerCause") ) {
                        	echo "Job triggered by event"
                        	//The json payload is enclosed in an event field
                      	  def eventContent = cause.event
                        	echo eventContent.fact.toString()
                        	//You can now use any json field send by the cURL command
                        	def fact = eventContent.fact.content
                        	echo "Fact is:" + fact.toString()
                    	}
                    	else if ( cause._class.contains("UserIdCause") ) {
                        	// The job can still be run manually, you may want to have different behavior.
                        	echo "Job triggered by user"
                    	}
                    	else {
                        	echo "Job triggered by something else"
                    	}
                	}
              }
        	}
      }
    }

Run the pipeline manually to validate the syntax, using the [\[bookmark-curl\]](#bookmark-curl) above, and the job should be triggered in few seconds.

Sample console output for a job triggered by a webhook:

    Triggered by event
    Running in Durability level: MAX_SURVIVABILITY
    [Pipeline] Start of Pipeline
    [Pipeline] stage
    [Pipeline] { (First stage)
    [Pipeline] script
    [Pipeline] {
    [Pipeline] echo
    Build triggered by:{"_class":"com.cloudbees.jenkins.plugins.pipeline.events.EventTriggerCause","event":{"my_source":"homemade","application":"real-fact","version":"1.3","fact":{"id":7368975833,"content":"Ada Lovelace was the first programmer, ever."}},"shortDescription":"Triggered by event"}
    [Pipeline] echo
    Job triggered by event
    [Pipeline] echo
    {"id":7368975833,"content":"Ada Lovelace was the first programmer, ever."}
    [Pipeline] echo
    Fact is:Ada Lovelace was the first programmer, ever.
    [Pipeline] }
    [Pipeline] // script
    [Pipeline] }
    [Pipeline] // stage
    [Pipeline] End of Pipeline
    Finished: SUCCESS

The event propagation is not immediate; you have to wait a few seconds.

When the JSON payload contains a field with a null value, Core Products remove the field in the JSON displayed on pipelines. So, if you send an event like:

    `curl -vvv \
    --data '{"my_source: "homemade","application":null}' \
    --header "Content-Type:application/json"\
    -XPOST /http://localhost:8400/webhooks/XoLZfgK/`

You will only have access to `{"my_source": "homemade"}` in the pipeline script.

[](#_use_a_publishing_pipeline_to_trigger_a_job)Use a publishing Pipeline to trigger a job
------------------------------------------------------------------------------------------

You can also use a publishing Pipeline to trigger a job. The `Cause` class will also be `EventTriggerCause`, so it will execute the same trigger as the webhook. You can use a field, like “application,” to distinguish the publishing Pipeline from the webhook.

    pipeline {
    	agent none
    	stages {
        	stage('First stage') {
            	steps {
                	publishEvent event:jsonEvent('{"my_source": "homemade", "application": "real-fact-job", "version": "1.4", "fact": { "id": 7368975833,"content": "Margaret Hamilton programmed the on-board flight software for Apollo missions." }}'), verbose: true
    
            	}
        	}
    	}
    }

Sample console output from a build triggered by a job with `publishEvent event:jsonEvent`:

    Triggered by event
    Running in Durability level: MAX_SURVIVABILITY
    [Pipeline] Start of Pipeline
    [Pipeline] stage
    [Pipeline] { (First stage)
    [Pipeline] script
    [Pipeline] {
    [Pipeline] echo
    Build triggered by:{"_class":"com.cloudbees.jenkins.plugins.pipeline.events.EventTriggerCause","event":{"my_source":"homemade","application":"real-fact-job","version":"1.4","fact":{"id":7368975833,"content":"Margaret Hamilton programmed the on-board flight software for Apollo missions."},"source":{"type":"JenkinsBuild","buildInfo":{"build":32,"job":"send-simple-event","jenkinsUrl":"http://localhost:8200/","instanceId":"09e3666bde9f5fa8a82c3fc889406c4f"}}},"shortDescription":"Triggered by event"}
    [Pipeline] echo
    Job triggered by event
    [Pipeline] echo
    {"id":7368975833,"content":"Margaret Hamilton programmed the on-board flight software for Apollo missions."}
    [Pipeline] echo
    Fact is:Margaret Hamilton programmed the on-board flight software for Apollo missions.
    [Pipeline] }
    [Pipeline] // script
    [Pipeline] }
    [Pipeline] // stage
    [Pipeline] End of Pipeline
    Finished: SUCCESS

In the sample log output you can see “source” is a reserved field for notification created by `publishEvent` and is automatically filled with data.