Lambda Code Pipeline S3 deployment

Lambda Pipeline S3 deployment

Use a Lambda function to trigger a Code Pipeline deployment to S3. ...

Figuring out the best way of triggering a Lambda Code Pipeline S3 depoyment is a key part of a serverless architecture.

It can be really useful when you want your app to update pending an update from a 3rd party service.

Step 1

Lambda Code Pipeline S3 deployment
Create a Code Pipeline called “Test”. Only specific requirements for set up are that you give the Pipeline’s Policy Full S3 Access and you set the deployment phase to target an S3 bucket.

Step 2

Lambda Code Pipeline S3 deployment
Create a Lambda function that has full access to AWS Code Pipeline in its Policy and also uses the below code that references the Code Pipeline called “Test”. Then run the Lambda funciton by clicking the Orange “Test” Button.

Step 3

Lambda Code Pipeline S3 deployment
The Lambda function should log a success and you should see your pipeline building on your Code Pipeline Dashboard. Once the Code Pipeline has finished building, you should see that the S3 bucket you set up has been updated.

I’ve posted the Lambda function below (with comments) so you can trigger a Lambda Code Pipeline S3 depoyment! I’ve also written a similar post to this on how to add authentication to S3 bucket with Lambda functions, that you may find helpful! Enjoy 😀

Lambda function

// require the AWS SDK
const AWS = require('aws-sdk');
// create an instance of code pipeline from the AWS SDK, so you can reference it
const codepipeline = new AWS.CodePipeline();

// The Lambda function that excecutes on run time
exports.handler = async (event) => {
   // javascript try statement
    try {
        // Await the result of the asynchronous function called build
        await Promise.all([
            // call the function build, passing through the name of the codepipeline to trigger
            build('Test')
        ]);
        // log the success of the pipeline trigger
        console.log('SUCCESS: triggered code pipeline');
    }
     // javascript catch statement 
     catch (error) {
        // log any occurred errors
        throw new Error(`FAILED: dataToS3 lambda. ${error.message}`);
    }
};

// asynchronous function called build
async function build(pipelineName) {
   // define parameters for the pipeline build, in this case only the pipeline's name is required
    const params = {
        name: pipelineName,
    };
    // await the confirmation that the code pipeline has been started
    await codepipeline.startPipelineExecution(params).promise();
}

Share this post