FMontano
FMontano

Reputation: 927

Building Docker images from Google Cloud Functions

As part of my CD pipeline, I am setting up a Google Cloud Function to handle new repo pushes, create docker images and push them to the registry. I have all working on a VM but there is no need to have one running 24x7 just for this.

So, looking over NodeJS reference library, I can't find a way to push an image to a registry using node. Seems like there is no registry or build sdk for node?

Basically, all I need is to execute this command from a cloud function: gcloud builds submit --tag gcr.io/my_project/my_image.

Upvotes: 0

Views: 1910

Answers (1)

Christopher P
Christopher P

Reputation: 1108

It's quite possible to do this using the Cloud Build API. Here's a simple example using the client libary for Node.js.

exports.createDockerBuild = async (req, res) => {
    const google = require('googleapis').google;
    const cloudbuild = google.cloudbuild({version: 'v1'});

    const client = await google.auth.getClient({
            scopes: ['https://www.googleapis.com/auth/cloud-platform']
    });
    const projectId = await google.auth.getProjectId();
    const resource = {
            "source": {
                    "storageSource": {
                            "bucket": "my-source-bucket",
                            "object": "my-nodejs-source.tar.gz"
                    }
            },
            "steps": [{
                    "name": "gcr.io/cloud-builders/docker",
                    "args": [
                            "build",
                            "-t",
                            "gcr.io/my-project-name/my-nodejs-image",
                            "standard-hello-world"
                    ]
            }],
            "images": ["gcr.io/$PROJECT_ID/my-nodejs-image"]
    };

    const params = {projectId, resource, auth: client};
    result= await cloudbuild.projects.builds.create(params);

    res.status(200).send("200 - Build Submitted");

};

My source code was in a bucket but you could pull it from a repo just as easily.

Bear in mind that you'll need to use the Node.js 8 beta runtime for the async stuff to work.

Upvotes: 2

Related Questions