Skip to content

Instantly share code, notes, and snippets.

@Timtech4u Timtech4u/index.js
Last active Aug 1, 2019

Embed
What would you like to do?
Cloud Function to Update Cloud Run Services
const request = require("request");
// Main function called by Cloud Functions trigger.
module.exports.updateCloudRunServices = (event, callback) => {
const build = eventToBuild(event.data);
// Check if push is to Dashboard source Code repo and if Cloud Build is successful
if (build.hasOwnProperty("source")) {
if (
build.source.repoSource.repoName === "dashboard" &&
build.status == "SUCCESS"
) {
updateDashboardRevisions();
}
}
};
const updateDashboardRevisions = () => {
let servicesListOption = {
method: "GET",
url:
"https://run.googleapis.com/v1alpha1/projects/mercuriemart/locations/us-central1/services",
headers: {
Authorization: `Bearer ${token}`, // @TODO: Ensure you pass your GCP API *token*
"Content-Type": "application/json"
}
};
// Get Cloud Run Services List
request(servicesListOption, function(error, response, body) {
if (error) throw new Error(error);
const services = JSON.parse(body);
let deploySteps = [];
// Iterate Through Services
services.items.forEach(element => {
let serviceName = element.metadata.name;
if (
element.metadata.annotations.hasOwnProperty(
"client.knative.dev/user-image"
)
) {
// Filter service based on Image and create new Build
if (
element["metadata"]["annotations"]["client.knative.dev/user-image"] ==
"gcr.io/project/dashboard:latest"
) {
deploySteps.push({
// Deploy New Revision to Service
name: "gcr.io/cloud-builders/gcloud",
args: [
"beta",
"run",
"deploy",
`${serviceName}`,
"--image",
"gcr.io/project/dashboard:latest",
"--region",
"us-central1",
"--allow-unauthenticated",
"--platform",
"managed"
]
});
}
}
});
// Update Cloud Run Services
let options = {
method: "POST",
url: "https://cloudbuild.googleapis.com/v1/projects/mercuriemart/builds",
headers: {
"cache-control": "no-cache",
Authorization: `Bearer ${token}`, // @TODO: Ensure you pass your GCP API *token*
"Content-Type": "application/json"
},
body: {
steps: deploySteps,
timeout: "1200s"
},
json: true
};
// Cloud Build Request to Deploy Revisions across Cloud Run Services
request(options, function(error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
});
};
{
"name": "updateRevisions",
"version": "0.0.1",
"description": "Update Cloud Run Services",
"main": "index.js",
"dependencies": {
"request": "^2.88.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.