Previous tutorial(http://cuneyt.aliustaoglu.biz/en/using-jenkins-with-aws-codecommit/) we have added our CodeCommit repository into Jenkins, but this Jenkins job could only be triggered manually. Now let's automate this and add a trigger on the AWS side to build Jenkins job when I push some commits to my repository.

There are a couple of ways to add a trigger.

  1. Amazon SNS
  2. Amazon Lambda

I don't want to add another plugin into Jenkins, so I've chosen AWS Lambda as my trigger.

Creating the Lambda function

Create a simple Lambda function with basic lambda execution role.

const http = require('http')

exports.handler = (event, context, callback) => {
    
    var auth = 'Basic ' + Buffer.from('JenkinsUserId:JenkinsAPIToken').toString('base64');
    
    var options = {
      host: 'example.com or ip address',
      path: '/jenkins/job/MyJenkinsJobName/job/RepoName/job/master/build?delay=0sec',
      port: '80',
      method: 'POST',
      headers: { 'Authorization': auth }
    };
    
   const req = http.request(options, (res) => {
        res.setEncoding('utf8');
        res.on('data', (chunk) => {
          // if you need the returned data modify here
        });
        res.on('end', () => {
          callback(null, 'Jenkins job triggered successfully')
        });
    });
    req.on('error', (e) => {
        console.log(e)
        callback(null, "An error occurred while triggering Jenkins job.");
    });
    req.end();
};

Get your Jenkins user id and API Token from "Configure" section in Jenkins. We will create the basic authentication credentials for Jenkins to authenticate the request we will send.

Configure your Jenkins path accordingly. You can find the exact path from the "Build Now" button in your pipeline.

build-now-jenkins

Simply right click the button and copy link address. Split this address into host and path to prepare your options paramater for the http request.

We've created the Lambda but still not linked it to CodeCommit. In your Lambda function go to "Designer" section and add a CodeCommit trigger. Enter your repository and branch names. Define when you want this trigger to be enabled. On creating/removing a branch, pushing to a branch or adding/removing tags. Or you can select them all. When you create this trigger it will insert the necessary AWS permissions. You can also create this trigger from the Settings section of the CodeCommit but there it won't create the permissions so you need to manually add it to your trigger.

You can test lambda manually to see if it will trigger Jenkins.

Now, make some changes and push your commits. Then see that in Jenkins this push created a build job in Jenkins.