Commit 1e29d26e authored by Muhammad Tehami's avatar Muhammad Tehami 💡

init

parents
# GCP Hackathon 2022 - Team Geek Speak Hertz
# Approve Artifact Deployment Apps Script
## Description
* This Apps Script get triggered by onSubmit event on the respective form of connected google sheet. The entry point for onSubmit event is onApprovalFormSubmit function in _main.gs_ file.
* This script publishes a message to Google Pub/Sub topic trigger-pipeline in 944919075758 project. The Pub/Sub message format is as follows:
```
{
timestamp: "10/15/2022 13:37:27",
intendID: "16-017185",
approve: "Yes",
approverEmail: "rasad@nisum.com"
}
```
## Setup
* Create a Google Form which have following fields (Turn on **Collect email addresses**)
* Email: Type _Email_
* Intend ID: Type _Short answer_
* Approve: Type _Multiple choice_ (Yes, No)
* Go to the respective Google Sheet of the Google Form. Click Extentions -> Apps Script. This will create a new Apps Script and connect it to the sheet.
* On Apps Script page there wil be file named _Code.gs_. Rename _Code.gs_ to _main.gs_ and copy _./main.gs_ contents from this directory to _main.gs_ on Apps Script. Create two new scripts on Apps Script with names _service.gs_ and _pubsub.gs_. Copy _./service.gs_ and _./pubsub.gs_ contents from this directory to respective Apps Script files.
* On Apps Script click Libraries -> Add a library. Put _1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF_ in Script ID textbox and click Look up, you will see OAuth2 version 42, click Add.
* Create a service account on Google Cloud Platform, assign Pub/Sub Publisher roler on trigger-pipeline topic. Generate OAuth 2.0 Client ID and copy Client ID/Client secret. Update CLIENT_ID and CLIENT_SECRET in _service.gs_ on Apps Script.
* Open _pubsub.gs_ file on Apps Script and run pubsub function. This will print an authorization URL of Google, copy this URL and decode it http://www.asiteaboutnothing.net/c_decode-url.html. Now look for the parameter starting with https://script.google.com/macros/d/ and ending with /usercallback. Copy this complete parameter.
* Google Cloud Platform -> Credentials -> OAuth 2.0 Client IDs -> Click your cient id. In "Authorized JavaScript origins" add https://script.google.com. In Authorized redirect URIs add the parameter you copied in previous step. Click Save.
* Go to Apps Script -> Project Settings and click Google Cloud Platform (GCP) Project -> Change project, put GCP Project number and click Set Project.
* Go to Apps Script -> Triggers -> Add Trigger, set parameter as follows and click Save.
* Choose which function to run: onApprovalFormSubmit
* Choose which deployment should run: Head
* Select event source: From spreadsheet
* Select event type: On form submit
* After 5 minutes, fill the Google Form and submit. Go to Apps Script -> Executions, you will see logs. Go to Google Pub/Sub topic trigger-pipeline and open respective subscription to pull messages. If everything worked fine you will be able to see message in the above defined format.
function onApprovalFormSubmit(e) {
var formData = e.namedValues;
var pubsubMessage = {
timestamp: formData['Timestamp'],
intendID: formData['Intend ID'],
approve: formData['Approve'],
approverEmail: formData['Email Address']
};
var res = pubsub("944919075758", "trigger-pipeline", pubsubMessage);
Logger.log("Intend approval pushed to Pub/Sub = " + formData['Intend ID']);
}
function pubsub(project, topic, data) {
var ss = SpreadsheetApp.getActive();
var service = getService();
if (!service.hasAccess()) {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log(authorizationUrl);
var template = HtmlService.createTemplate(
'<a href="<?= authorizationUrl ?>" target="_blank">Authorize</a>. ' +
'Reopen the sidebar when the authorization is complete.');
template.authorizationUrl = authorizationUrl;
var page = template.evaluate();
SpreadsheetApp.getUi().showSidebar(page);
} else {
var url = 'https://pubsub.googleapis.com/v1/projects/[PROJECT]/topics/[TOPIC]:publish'
.replace("[TOPIC]", topic)
.replace("[PROJECT]", project);
// The data attribute is of 'string' type and needs to be base64 Encoded!
var body = {
messages: [
{
data: Utilities.base64Encode(JSON.stringify(data))
}
]
};
var response = UrlFetchApp.fetch(url, {
method: "POST",
contentType: 'application/json',
muteHttpExceptions: true,
payload: JSON.stringify(body),
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
var message = JSON.stringify(result);
Logger.log(response);
return {
log: message
}
}
}
var CLIENT_ID = 'xxxxxxxxxxxxxxxx.apps.googleusercontent.com';
var CLIENT_SECRET = 'xxxxxxxxxxxxxxxx';
function getService() {
return OAuth2.createService('MyPubSub')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setCallbackFunction('authCallback')
.setPropertyStore(PropertiesService.getUserProperties())
.setScope(['https://www.googleapis.com/auth/cloud-platform','https://www.googleapis.com/auth/pubsub','https://www.googleapis.com/auth/script.external_request'])
.setParam('access_type', 'offline')
.setParam('approval_prompt', 'force')
.setParam('login_hint', Session.getActiveUser().getEmail());
}
function authCallback(request) {
var service = getService();
var isAuthorized = service.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}
function reset() {
var service = getService();
service.reset();
}
function logRedirectUri() {
var service = getService();
Logger.log(service.getRedirectUri());
}
# Request Artifact Deployment Apps Script
## Description
* This Apps Script get triggered by onSubmit event on the respective form of connected google sheet. The entry point for onSubmit event is onRequestFormSubmit function in _main.gs_ file.
* This script publishes a message to Google Pub/Sub topic trigger-email in 944919075758 project. The Pub/Sub message format is as follows:
```
{
timestamp: "10/14/2022 20:41:12",
intendID: "16-017185",
projectName: "marketplace",
artifactName: "app-1",
artifactVersion: "0.0.1",
environment: "DEV",
requesterEmail: "mtehami@nisum.com"
}
```
## Setup
* Create a Google Form which have following fields (Turn on **Collect email addresses**)
* Email: Type _Email_
* Project Name: Type _Short answer_
* Artifact Name: Type _Short answer_
* Artifact Version: Type _Short answer_
* Environment: Type _Multiple choice_ (DEV, QA, PERF, PROD)
* Go to the respective Google Sheet of the Google Form. Create a new column "Intend ID" and put following formula in the bellow cell:
```
=arrayformula( if( len(A2:A), "" & text(row(A2:A) - row(A2) + 2, "000") & RIGHT(VALUE(A2:A), 3), iferror(1/0) ) )
```
* On Google Sheet click Extentions -> Apps Script. This will create a new Apps Script and connect it to the sheet.
* On Apps Script page there wil be file named _Code.gs_. Rename _Code.gs_ to _main.gs_ and copy _./main.gs_ contents from this directory to _main.gs_ on Apps Script. Create two new scripts on Apps Script with names _service.gs_ and _pubsub.gs_. Copy _./service.gs_ and _./pubsub.gs_ contents from this directory to respective Apps Script files.
* On Apps Script click Libraries -> Add a library. Put _1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF_ in Script ID textbox and click Look up, you will see OAuth2 version 42, click Add.
* Create a service account on Google Cloud Platform, assign Pub/Sub Publisher roler on trigger-email topic. Generate OAuth 2.0 Client ID and copy Client ID/Client secret. Update CLIENT_ID and CLIENT_SECRET in _service.gs_ on Apps Script.
* Open _pubsub.gs_ file on Apps Script and run pubsub function. This will print an authorization URL of Google, copy this URL and decode it http://www.asiteaboutnothing.net/c_decode-url.html. Now look for the parameter starting with https://script.google.com/macros/d/ and ending with /usercallback. Copy this complete parameter.
* Google Cloud Platform -> Credentials -> OAuth 2.0 Client IDs -> Click your cient id. In "Authorized JavaScript origins" add https://script.google.com. In Authorized redirect URIs add the parameter you copied in previous step. Click Save.
* Go to Apps Script -> Project Settings and click Google Cloud Platform (GCP) Project -> Change project, put GCP Project number and click Set Project.
* Go to Apps Script -> Triggers -> Add Trigger, set parameter as follows and click Save.
* Choose which function to run: onRequestFormSubmit
* Choose which deployment should run: Head
* Select event source: From spreadsheet
* Select event type: On form submit
* After 5 minutes, fill the Google Form and submit. Go to Apps Script -> Executions, you will see logs. Go to Google Pub/Sub topic trigger-email and open respective subscription to pull messages. If everything worked fine you will be able to see message in the above defined format.
function onRequestFormSubmit(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var sheetData = sheet.getDataRange().getValues();
var formData = e.namedValues;
var rowNumber = parseInt(e.range.getRow() - 1).toFixed(0);
var intendID = rowNumber + "-" + sheetData[rowNumber][6];
var pubsubMessage = {
timestamp: formData['Timestamp'],
intendID: intendID,
projectName: formData['Project Name'],
artifactName: formData['Artifact Name'],
artifactVersion: formData['Artifact Version'],
environment: formData['Environment'],
requesterEmail: formData['Email Address']
};
var res = pubsub("944919075758", "trigger-email", pubsubMessage);
Logger.log("Intend request pushed to Pub/Sub = " + intendID);
}
function pubsub(project, topic, data) {
var ss = SpreadsheetApp.getActive();
var service = getService();
if (!service.hasAccess()) {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log(authorizationUrl);
var template = HtmlService.createTemplate(
'<a href="<?= authorizationUrl ?>" target="_blank">Authorize</a>. ' +
'Reopen the sidebar when the authorization is complete.');
template.authorizationUrl = authorizationUrl;
var page = template.evaluate();
SpreadsheetApp.getUi().showSidebar(page);
} else {
var url = 'https://pubsub.googleapis.com/v1/projects/[PROJECT]/topics/[TOPIC]:publish'
.replace("[TOPIC]", topic)
.replace("[PROJECT]", project);
// The data attribute is of 'string' type and needs to be base64 Encoded!
var body = {
messages: [
{
data: Utilities.base64Encode(JSON.stringify(data))
}
]
};
var response = UrlFetchApp.fetch(url, {
method: "POST",
contentType: 'application/json',
muteHttpExceptions: true,
payload: JSON.stringify(body),
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
var message = JSON.stringify(result);
Logger.log(response);
return {
log: message
}
}
}
var CLIENT_ID = 'xxxxxxxxxxxxxxxx.apps.googleusercontent.com';
var CLIENT_SECRET = 'xxxxxxxxxxxxxxxx';
function getService() {
return OAuth2.createService('MyPubSub')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setCallbackFunction('authCallback')
.setPropertyStore(PropertiesService.getUserProperties())
.setScope(['https://www.googleapis.com/auth/cloud-platform','https://www.googleapis.com/auth/pubsub','https://www.googleapis.com/auth/script.external_request'])
.setParam('access_type', 'offline')
.setParam('approval_prompt', 'force')
.setParam('login_hint', Session.getActiveUser().getEmail());
}
function authCallback(request) {
var service = getService();
var isAuthorized = service.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}
function reset() {
var service = getService();
service.reset();
}
function logRedirectUri() {
var service = getService();
Logger.log(service.getRedirectUri());
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment