GCP: Cloud Functions

Slack通知用のCloud Functionを作る

package.jsonを作る。

{
    "name": "cloud-build-notification",
    "version": "0.0.1",
    "description": "Slack integration for Google Cloud Build, using Google Cloud Functions",
    "main": "index.js",
    "dependencies": {
        "@slack/client": "3.9.0"
    }
}

index.jsを作る。

const IncomingWebhook = require('@slack/client').IncomingWebhook;
const webhook = new IncomingWebhook(process.env.SLACK_WEBHOOK_URL);

// subscribe is the main function called by Cloud Functions.
module.exports.subscribe = (event, callback) => {
    const build = eventToBuild(event.data);

    // Skip if the current status is not in the status list.
    // Add additional statues to list if you'd like:
    // QUEUED, WORKING, SUCCESS, FAILURE,
    // INTERNAL_ERROR, TIMEOUT, CANCELLED
    const status = ['SUCCESS', 'FAILURE', 'INTERNAL_ERROR', 'TIMEOUT'];
    if (status.indexOf(build.status) === -1) {
        return callback();
    }

    // Send message to Slack.
    const message = createSlackMessage(build);
    webhook.send(message, callback);
};

// eventToBuild transforms pubsub event message to a build object.
const eventToBuild = (data) => {
    return JSON.parse(new Buffer(data, 'base64').toString());
}

// createSlackMessage creates a message from a build object.
const createSlackMessage = (build) => {
    let message = {
        text: `Build \`${build.id}\``,
        mrkdwn: true,
        attachments: [
            {
                title: 'Build logs',
                title_link: build.logUrl,
                fields: [{
                    title: 'Status',
                    value: build.status
                }, {
                    title: 'Branch',
                    value: build.substitutions.BRANCH_NAME
                }, {
                    title: 'Repository',
                    value: build.substitutions.REPO_NAME
                }]
            }
        ]
    };
    return message
}

参考: https://cloud.google.com/cloud-build/docs/configure-third-party-notifications?hl=ja

デプロイする

デプロイする前にCloud Function用のCloud Storageを作る必要がある。
バケット名は世界中でユニークでないといけないので注意。
SlackのWebhook URLはココで新しいアプリを作成したあと、Incoming Webhooksから生成できる。

BUCKET='<cloud storage bucket name>'
gsutil mb gs://$BUCKET

SLACK_WEBHOOK_URL='<your webhook url>'
gcloud functions deploy cloud-build-notification-slack \
    --stage-bucket $BUCKET \
    --entry-point subscribe \
    --trigger-topic cloud-builds \
    --runtime nodejs8 \
    --set-env-vars SLACK_WEBHOOK_URL=$SLACK_WEBHOOK_URL

ログを確認する

gcloud beta functions logs read

GitHubのwebhook契機で実行

状態をもたせる

Cloud Datastore、Cloud Firestore、Cloud Storageなどを利用してデータを保持する。

Ref:
https://cloud.google.com/functions/docs/concepts/exec?hl=ja