DEV Community

Kay Gosho
Kay Gosho

Posted on

Kick CircleCI from Slack command + Google Apps Script

I've automated app deployment with CircleCI + Slack + Google Apps Script.

  1. Create slack bot

  2. Get Slack Webhook token

  3. Create CircleCI Job

  4. Get CircleCI Token

  5. Create Google Apps Script:

const GITHUB_REPO = 'account/repo'
const CIRCLE_TOKEN = '***'
const SLACK_WEBHOOK_URL = 'https://hooks.slack.com/services/***/***/***'

function doPost(e) {
  const branch = e.parameters.text[0];

  _deployToCircle('deploy', branch);

  return ContentService.createTextOutput('ok');
}

function _deployToCircle(circleJob, branch) {
  const url = 'https://circleci.com/api/v1.1/project/' + GITHUB_REPO + 'tree/' + branch + '?circle-token=' + CIRCLE_TOKEN;
  const payload = {
    build_parameters: {
      CIRCLE_JOB: circleJob,
      STAGING: 'true', // additional params
    }
  }
  const circleRes = UrlFetchApp.fetch(url, {
    method: 'post',
    muteHttpExceptions: true,
    contentType: 'application/json',
    payload: JSON.stringify(payload),
  });
  Logger.log(circleRes.getResponseCode());
  Logger.log(circleRes.getContent());

  const message = 'branch deploy start: ' + branch + '\nCircleCI response: ' + circleRes.getResponseCode()

  const slackRes = UrlFetchApp.fetch(SLACK_WEBHOOK_URL, {
    method: 'post',
    contentType: 'application/json',
    payload: JSON.stringify({ text: message }),
  });
  Logger.log(JSON.stringify(slackRes));
}

function doPostTest() {
  doPost({
    parameters: {
      text: ['branch_name_to_deploy'],
    }
  })
}
Enter fullscreen mode Exit fullscreen mode
  1. Set Slack command to kick the Google Apps Script

Top comments (0)