0
votes

How can I have Aws CodePipeline be triggered by multiple sources? Imagine I want to have the same pipeline to be triggered whenever I push to two different repositories? Plus, the build stage must know which repository triggered the pipeline and pull from the right repository

1
What problem are you trying to solve?George Rushby

1 Answers

0
votes

Well, it will depend on the pipeline itself. Aws says codepipelines are made per project only. However, one way you could tackle this problem is by:

  • building a lambda function what triggers codebuild
  • the lambda function will have as many triggers as the number of repositories you want to trigger the same pipeline
  • the lambda function will pass environment variables to CodeBuild and trigger its execution
  • CodeBuild will work out which repo to pull from depending on the value of the environment variable

How-To:

const AWS = require('aws-sdk'); // importing aws sdk
const fs = require('fs'); // importing fs to read our json file
const handler = (event, context) => {
  AWS.config.update({region:'us-east-2'}); // your region can vary from mine
  var codebuild = new AWS.CodeBuild(); // creating codebuild instance
  //this is just so you can see aws sdk loaded properly so we are going to have it print its credentials. This is not required but shows us that the sdk loaded correctly
  AWS.config.getCredentials(function(err) {
  if (err) console.log(err.stack);
  // credentials not loaded
  else {
    console.log("Access key:", AWS.config.credentials.accessKeyId);
    console.log("Secret access key:", AWS.config.credentials.secretAccessKey);
  }
});

var repositories = JSON.parse(fs.readFileSync('repositories.json').toString());
var selectedRepo = event.Records[0].eventTriggerName;

var params = {
        projectName: 'lib-patcher-build', /* required */
        artifactsOverride: {
            type: 'CODEPIPELINE', /* required*/
          },
        environmentVariablesOverride: [
          {
            name: 'name-of-the-environment-variable', /* required */
            value: 'its-value', /* required */
            type: 'PLAINTEXT'
          },
          {
            name: 'repo-url', /* required */
            value: 'repositories[selectedRepo].url', /* required */
            type: 'PLAINTEXT'
          }
          /* more items */
        ],
      };
      codebuild.startBuild(params, function(err, data) {
        if (err) console.log(err, err.stack); // an error occurred
        else     console.log(data);           // successful response
      });

};

exports.handler = handler;