Use POST Commit Hook with Perforce Triggers

Article ID:219152268
2 minute readKnowledge base

Issue

  • How to create POST commit hook to integrate Jenkins with Perforce

Environment

  • CloudBees Jenkins Enterprise

  • Jenkins

  • P4 Plugin

Resolution

Since the release of the version 1.3.9 of the P4 Plugin, it is now possible to create "POST Commit Hook" for Perforce jobs based on a P4Port.

How it Works

Jenkins is listening for HTTP POST requests at https://my.jenkins.url/p4/change. A specific JSON payload needs to be POSTed following this schema:

{"change":"12345","p4port":"localhost:1666"}

When such request is POSTed, all jobs that are configured to be triggered by Perforce and that match this p4port will be "triggered". This p4port is specified in the Perforce Credentials:

p4-job-p4port

Jenkins actually performs a polling and, if changes are detected, a build is triggered.

How to Use

In order to achieve this, you need to:

  • Configure your job(s) to listen to Perforce triggers

  • Create a P4 Triggers

Configure the Job

In order to have a job triggered by a Perforce, tick the Perforce triggered build. checkbox in the Build Triggers section of the Job:

p4-job-trigger

Create a P4 Trigger

On the Perforce server, it is possible to create triggers or, in other words, scripts to be run on a particular event - for example after a change-commit.

  • First we need to create a script that POST the correct payload to our Jenkins endpoint

  • We need to define a P4 trigger that execute this script on a change-commit

a) Create a Script

The script needs to POST the payload to the Jenkins server. For example, the following is a sample script $P4_HOME/submit.sh that use cURL:

#!/bin/bash

# The first argument is the change number
CHANGE=$1

# POST the payload
curl --header 'Content-Type: application/json' \
	 --request POST \
 	 --data "{\"change\":$CHANGE, \"p4port\":\"localhost:1666\"}" \
	 https://localhost:8080/p4/change

b) Create the Trigger

You need to be a P4 administrator in order to add triggers to you P4 server

A trigger maps an event in a specified location to a script. In order to add triggers, you need to run the following command:

p4 triggers

This open a file in the command line. You need to add you trigger at the end of the fil. For example, the following add a trigger on any change-commit event under //depot/...:

[...]

Triggers:
    global-change change-commit //depot/... "$P4_HOME/submit.sh %change%"

Every time a change is committed to P4, this trigger executes the script $P4_HOME/submit.sh with the change number in argument: %change%. The attribute global-change is the name of the trigger and you can specify whatever you want.

Further Documentation

The P4 Plugin documentation:

Multiple triggers can be defined with more specific locations and/or on different events. More information can be found at the following links:

This feature is a important improvement to overcome the issue(s) mentioned in: