Victor
Victor

Reputation: 395

Trigger Jenkins builds by pushing to CodeCommit

I created a repository git aws codeCommit, I need when I push something on branch X to launch a job Jenkins.

In the picture is my configuration:

enter image description here

But it doesn't work. When I push source code into my branch codeCommit nothing happens. Would do you have any ideas?

Upvotes: 2

Views: 9267

Answers (4)

Steven
Steven

Reputation: 2275

Another solution using the git plugin push notifications. Is the following lambda, which you can register as a trigger to the repo.

Benefits are: jenkins jobs do not need to be adapted (assuming they have SCM polling enabled), no special credentials and the jobs do not need to be known upfront.

const url = require('url');
const HEAD_PREFIX='refs/heads/';
const JENKINS_URL=url.parse(url.resolve(process.env.JENKINS_URL, "git/notifyCommit"));
const CLONE_PROTOCOL=process.env.CLONE_PROTOCOL ? process.env.CLONE_PROTOCOL : "ssh";
const http = require(JENKINS_URL.protocol.split(":")[0]);

exports.handler = async (event) => {
    await Promise.all(event.Records.map(handleRecord));
};

async function handleRecord(record) {
    var repo = cloneUrl(record.eventSourceARN);
    await Promise.all(
        record.codecommit.references
            .filter(ref => ref.ref.startsWith(HEAD_PREFIX))
            .map(ref => pollJenkins(repo, ref))
    );
}

function cloneUrl(repoArn) {
    var splitted = repoArn.split(":");
    return `${CLONE_PROTOCOL}://git-codecommit.${splitted[3]}.amazonaws.com/v1/repos/${splitted[5]}`
}

function pollJenkins(repo, ref) {
    const path = url.format(Object.assign({}, JENKINS_URL, {
        query: {
            url: repo,
            branches: ref.ref.substring(HEAD_PREFIX.length),
            sha1: ref.commit
        }
    }));
    return new Promise(function(resolve, reject){
        const req = http.get(path, res => {
            if (res.statusCode > 100 && res.statusCode < 300) {
                console.log("success: " + path);
                resolve();
                res.resume();
            } else {
                res.on('data', (chunk) => {
                  console.log(`BODY: ${chunk}`);
                });
                res.on('end', () => {
                  reject("Unexpected status code " + res.statusCode);
                });
            }
        });
        req.on('error', reject);
   });
}

Provide the JENKINS_URL and codecommit CLONE_PROTOCOL as environment variables.

Upvotes: 0

I use AWS Lambda to trigger Jenkins when I push something to CodeCommit. You know you can manually trigger Jenkins using cURL:

curl --request POST --url 'http://example.com/jenkins/job/MYJOBNAME/job/MYREPONAME/job/master/build?delay=0sec' --user JenkinsUserId:JenkinsAPIToken

Just turn this cURL into POST request in nodejs.

  • Find your Jenkins credentials in Configure section.
  • Create a new Lambda using NodeJS
  • Add a CodeCommit trigger to this Lambda.
  • Paste below code into your Lambda and replace credentials as necessary
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();
};

Upvotes: 0

3z33etm
3z33etm

Reputation: 1113

codecommit doesn't support triggering Jenkins like GitHub does. But you can set up Jenkins to poll codecommit

https://aws.amazon.com/blogs/devops/integrating-aws-codecommit-with-jenkins/

Upvotes: 1

Related Questions