🎥 Make videos programmatically with React
split out installed into functions, zipped for download
Matt McGillivray35b20fccfcdf
diff --git a/packages/cloudrun/gcpInstaller/components/checkEnvFile.mjs b/packages/cloudrun/gcpInstaller/components/checkEnvFile.mjsnew file mode 100644index 0000000000..f249bfa745--- /dev/null+++ b/packages/cloudrun/gcpInstaller/components/checkEnvFile.mjs@@ -0,0 +1,51 @@+import { execSync } from "child_process";+import { existsSync } from "fs";+import { colorCode } from "./colorCodes.mjs";+import readline from "readline";++function deleteEnvPrompt() {+ return new Promise((resolve) => {+ const rl = readline.createInterface({+ input: process.stdin,+ output: process.stdout,+ });++ rl.question(+ `${colorCode.redText}.env file exists in this directory. Delete and create new .env file [yes, no]? ${colorCode.blueText}`,+ async (answer) => {+ // reset terminal color+ rl.output.write(`\n${colorCode.resetText}`);+ rl.close();++ if (["yes", "y"].indexOf(answer.trim().toLowerCase()) >= 0) {+ execSync("rm .env");+ execSync(+ `echo "${colorCode.redText}Deleted .env file.${colorCode.resetText}"`+ );+ return resolve(true);+ }++ if (["no", "n"].indexOf(answer.trim().toLowerCase()) >= 0) {+ execSync('echo ".env file present, and not deleted, exiting..."', {+ stdio: "inherit",+ });+ process.exit(1);+ }++ console.log("Invalid response.\n");+ const result = await deleteEnvPrompt();++ resolve(result);+ }+ );+ });+}++export async function checkEnvFile() {+ /****************************************+ * Check for existing .env file+ ****************************************/+ if (existsSync(".env")) {+ await deleteEnvPrompt();+ }+}diff --git a/packages/cloudrun/gcpInstaller/components/checkTerraformStateFile.mjs b/packages/cloudrun/gcpInstaller/components/checkTerraformStateFile.mjsnew file mode 100644index 0000000000..25339e091f--- /dev/null+++ b/packages/cloudrun/gcpInstaller/components/checkTerraformStateFile.mjs@@ -0,0 +1,41 @@+import { execSync } from "child_process";+import { existsSync, readFileSync } from "fs";+import { colorCode } from "./colorCodes.mjs";++export function checkTerraformStateFile(projectID) {+ /****************************************+ * Check for existing Terraform State+ ****************************************/++ if (existsSync("terraform.tfstate")) {+ execSync(+ 'echo "Terraform State file exists. Checking it is for the current Remotion project...\n"',+ { stdio: "inherit" }+ );++ const tfstate = JSON.parse(readFileSync("terraform.tfstate", "utf-8"));++ const tfstateProject = tfstate.outputs?.remotion_project_id?.value;++ if (tfstateProject === undefined) {+ execSync(+ `echo "${colorCode.redText}Terraform state file is not from a Remotion project.\nChange directory, or delete all existing terraform files within the current directory, before trying again.\nTo delete all terraform files, run: ${colorCode.resetText}rm -rf .terraform terraform.tfstate terraform.tfstate.backup .terraform.lock.hcl terraform.tfstate.*.backup"`,+ { stdio: "inherit" }+ );+ process.exit(1);+ }++ if (tfstateProject === projectID) {+ execSync(+ `echo "${colorCode.greenText}Terraform state file is for the current Remotion project - ${projectID}. Continuing...${colorCode.resetText}\n"`,+ { stdio: "inherit" }+ );+ } else {+ execSync(+ `echo "${colorCode.redText}Terraform state file is for project ${colorCode.redBackground}${tfstateProject}${colorCode.redText}.\nThe current project is ${colorCode.redBackground}${projectID}${colorCode.redText}.\nChange directory, or delete all existing terraform files within the current directory, before trying again.${colorCode.resetText}"`,+ { stdio: "inherit" }+ );+ process.exit(1);+ }+ }+}diff --git a/packages/cloudrun/gcpInstaller/components/colorCodes.mjs b/packages/cloudrun/gcpInstaller/components/colorCodes.mjsnew file mode 100644index 0000000000..6aa81b6149--- /dev/null+++ b/packages/cloudrun/gcpInstaller/components/colorCodes.mjs@@ -0,0 +1,18 @@+/****************************************+ * Text colours codes+ ****************************************/+const resetText = "\u001b[0m";+const greenText = `${resetText}\u001b[32;1m`;+const blueText = `${resetText}\u001b[34;1m`;+const redText = `${resetText}\u001b[31;1m`;+const redBackground = `${resetText}\u001b[41;1m`;+const greenBackground = `${resetText}\u001b[42;1m`;++export const colorCode = {+ resetText,+ greenText,+ blueText,+ redText,+ redBackground,+ greenBackground,+};diff --git a/packages/cloudrun/gcpInstaller/components/generateEnvPrompt.mjs b/packages/cloudrun/gcpInstaller/components/generateEnvPrompt.mjsnew file mode 100644index 0000000000..cdf97a1091--- /dev/null+++ b/packages/cloudrun/gcpInstaller/components/generateEnvPrompt.mjs@@ -0,0 +1,31 @@+import readline from "readline";+import { colorCode } from "./colorCodes.mjs";++export function generateEnvPrompt() {+ return new Promise((resolve) => {+ const rl = readline.createInterface({+ input: process.stdin,+ output: process.stdout,+ });++ rl.question(+ `\n${colorCode.greenText}Do you want to generate the .env file for your code base? ${colorCode.blueText}`,+ async (answer) => {+ // reset terminal color+ rl.output.write(`${colorCode.resetText}`);+ rl.close();++ if (["yes", "y"].indexOf(answer.trim().toLowerCase()) >= 0)+ return resolve(true);++ if (["no", "n"].indexOf(answer.trim().toLowerCase()) >= 0)+ return resolve(false);++ console.log("Invalid response.");+ const result = await generateEnvPrompt();++ resolve(result);+ }+ );+ });+}diff --git a/packages/cloudrun/gcpInstaller/components/remotionVersionPrompt.mjs b/packages/cloudrun/gcpInstaller/components/remotionVersionPrompt.mjsnew file mode 100644index 0000000000..8e4a4973d7--- /dev/null+++ b/packages/cloudrun/gcpInstaller/components/remotionVersionPrompt.mjs@@ -0,0 +1,60 @@+import { execSync } from "child_process";+import readline from "readline";+import { colorCode } from "./colorCodes.mjs";++export function remotionVersionPrompt() {+ return new Promise((resolve) => {+ // regex to ensure remotionVersion is in semver format+ const semverRegex = new RegExp(+ /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,+ "i"+ );++ const rl = readline.createInterface({+ input: process.stdin,+ output: process.stdout,+ });++ rl.question(+ `What version of Remotion do you want to use (format: 1.0.0)? ${colorCode.blueText}`,+ async (answer) => {+ rl.write(`\n${colorCode.resetText}`);+ rl.close();++ let fileError = false;+ if (semverRegex.test(answer.trim())) {+ try {+ execSync(+ `gcloud storage ls gs://remotion-sa/${answer.trim()}/sa-permissions.json`+ );+ return resolve(answer.trim());+ } catch {+ fileError = true;+ }+ }++ if (fileError) {+ console.log(+ `${+ colorCode.redText+ }Cannot find permissions file that matches version ${answer.trim()}.\n${+ colorCode.resetText+ }`+ );+ } else {+ console.log(+ `${+ colorCode.redText+ }${answer.trim()} is not a valid semver version number.\n${+ colorCode.resetText+ }`+ );+ }++ const result = await remotionVersionPrompt();++ resolve(result);+ }+ );+ });+}diff --git a/packages/cloudrun/gcpInstaller/components/splashScreen.mjs b/packages/cloudrun/gcpInstaller/components/splashScreen.mjsnew file mode 100644index 0000000000..370eeb9c48--- /dev/null+++ b/packages/cloudrun/gcpInstaller/components/splashScreen.mjs@@ -0,0 +1,21 @@+import { execSync } from "child_process";+import { colorCode } from "./colorCodes.mjs";+/****************************************+ * Splash screen for Remotion Cloud Run+ ****************************************/++export function cloudRunSplashScreen() {+ execSync(+ `echo "\n\n${colorCode.greenBackground} "`,+ {+ stdio: "inherit",+ }+ );+ execSync('echo " GCP project setup for Remotion Cloud Run "', {+ stdio: "inherit",+ });+ execSync(+ `echo " \n\n${colorCode.resetText}"`,+ { stdio: "inherit" }+ );+}diff --git a/packages/cloudrun/gcpInstaller/components/taskPrompt.mjs b/packages/cloudrun/gcpInstaller/components/taskPrompt.mjsnew file mode 100644index 0000000000..2d6b492d40--- /dev/null+++ b/packages/cloudrun/gcpInstaller/components/taskPrompt.mjs@@ -0,0 +1,56 @@+import { execSync } from "child_process";+import readline from "readline";+import { colorCode } from "./colorCodes.mjs";++export function taskPrompt(projectID) {+ return new Promise((resolve) => {+ const rl = readline.createInterface({+ input: process.stdin,+ output: process.stdout,+ });++ rl.question(+ `What would you like to do?\n[1] Setup the GCP project ${projectID} as a Remotion Cloud Run environment.\n[2] ${projectID} is already set up for Remotion, update to a newer Remotion version.\n[3] ${projectID} is already set up for Remotion, generate a new .env file or manage keys for the Remotion Service Account.\n${colorCode.blueText}`,+ async (answer) => {+ // reset terminal color+ rl.output.write(`\n${colorCode.resetText}`);++ if (answer.trim() === "1") {+ rl.output.write(+ `${colorCode.blueText}<Terraform selected>\n\n${colorCode.resetText}`+ );+ rl.close();+ return resolve("runTerraform");+ }++ if (answer.trim() === "2") {+ rl.output.write(+ `${colorCode.blueText}<Update Remotion selected>\n\n${colorCode.resetText}`+ );+ rl.close();+ return resolve("updateRemotion");+ }++ if (answer.trim() === "3") {+ rl.output.write(+ `${colorCode.blueText}<.env creation selected>\n\n${colorCode.resetText}`+ );+ rl.close();+ return resolve("generateEnv");+ }++ rl.close();+ execSync(+ `echo "${colorCode.redText}Invalid selection. Please enter 1, 2 or 3.\n${colorCode.resetText}"`,+ {+ stdio: "inherit",+ }+ );++ const result = await taskPrompt();++ resolve(result);+ }+ );+ });+}diff --git a/packages/cloudrun/gcpInstaller/components/terraformApplyPrompt.mjs b/packages/cloudrun/gcpInstaller/components/terraformApplyPrompt.mjsnew file mode 100644index 0000000000..ec81b2c80f--- /dev/null+++ b/packages/cloudrun/gcpInstaller/components/terraformApplyPrompt.mjs@@ -0,0 +1,31 @@+import readline from "readline";+import { colorCode } from "./colorCodes.mjs";++export function terraformApplyPrompt() {+ return new Promise((resolve) => {+ const rl = readline.createInterface({+ input: process.stdin,+ output: process.stdout,+ });++ rl.question(+ `\n${colorCode.greenText}Do you want to apply the above plan? ${colorCode.blueText}`,+ async (answer) => {+ // reset terminal color+ rl.output.write(colorCode.resetText);+ rl.close();++ if (["yes", "y"].indexOf(answer.trim().toLowerCase()) >= 0)+ return resolve(true);++ if (["no", "n"].indexOf(answer.trim().toLowerCase()) >= 0)+ return resolve(false);++ console.log("Invalid response.");+ const result = await terraformApplyPrompt();++ resolve(result);+ }+ );+ });+}diff --git a/packages/cloudrun/gcpInstaller/install.mjs b/packages/cloudrun/gcpInstaller/install.mjsnew file mode 100644index 0000000000..19f77e2705--- /dev/null+++ b/packages/cloudrun/gcpInstaller/install.mjs@@ -0,0 +1,56 @@+import { execSync } from "child_process";+// Components+import { colorCode } from "./components/colorCodes.mjs";+import { cloudRunSplashScreen } from "./components/splashScreen.mjs";+import { taskPrompt } from "./components/taskPrompt.mjs";+// Tasks+import { generateEnv } from "./tasks/generateEnv.mjs";+import { updateRemotion } from "./tasks/updateRemotion.mjs";+import { setupGcpProject } from "./tasks/setupGcpProject.mjs";++/****************************************+ * Splash screen for Remotion Cloud Run+ ****************************************/+cloudRunSplashScreen();++/****************************************+ * Set project ID for Terraform and gcloud commands+ ****************************************/+execSync(`echo "Retrieving current Project ID..."`, {+ stdio: "inherit",+});++const projectID = execSync("gcloud config get-value project", {+ stdio: ["inherit", "pipe", "pipe"],+})+ .toString()+ .trim();++execSync(+ `echo "Project set to ${colorCode.blueText}${projectID}${colorCode.resetText}\n"`,+ {+ stdio: "inherit",+ }+);++/****************************************+ * Check task the user is trying to complete+ ****************************************/+const selection = await taskPrompt(projectID);++switch (selection) {+ case "runTerraform":+ await setupGcpProject(projectID);+ break;++ case "updateRemotion":+ await updateRemotion(projectID);+ break;++ case "generateEnv":+ await generateEnv(projectID);+ break;++ default:+ break;+}diff --git a/packages/cloudrun/gcpInstaller/installer.zip b/packages/cloudrun/gcpInstaller/installer.zipnew file mode 100644index 0000000000..51a6eb9516Binary files /dev/null and b/packages/cloudrun/gcpInstaller/installer.zip differdiff --git a/packages/cloudrun/gcpInstaller/main.tf b/packages/cloudrun/gcpInstaller/main.tfnew file mode 100644index 0000000000..19e448c615--- /dev/null+++ b/packages/cloudrun/gcpInstaller/main.tf@@ -0,0 +1,82 @@+terraform {+ required_providers {+ google = {+ source = "hashicorp/google"+ version = "4.58.0"+ }+ }++ required_version = ">= 1.4.1"+}++variable "project_id" {+ type = string+ description = "The ID of the project in which the resources will be created."+}++variable "remotion_version" {+ type = string+ description = "The version of Remotion being deployed."+}++variable "service_account_exists" {+ type = bool+ description = "If the service account already exists, no need to re-create."+}+++provider "google" {+ project = var.project_id+ region = "us-central1"+ zone = "us-central1-c"+}++data "http" "permissions" {+ url = "https://storage.googleapis.com/remotion-sa/${var.remotion_version}/sa-permissions.json"+}++locals {+ # permissions = jsondecode(file("${path.module}/../src/shared/sa-permissions.json"))+ cloudrun-permissions = jsondecode(data.http.permissions.response_body)+ service-account-email = "remotion-sa@${var.project_id}.iam.gserviceaccount.com"+}++# Create an IAM role+resource "google_project_iam_custom_role" "remotion_sa" {+ role_id = "RemotionSA"+ title = "Remotion API Service Account"+ description = "Allow the service account to manage necessary resources for Remotion Cloud Run rendering."+ permissions = local.cloudrun-permissions.list+}++# Create a service account+resource "google_service_account" "remotion_sa" {+ count = var.service_account_exists ? 0 : 1 // if the service account already exists, don't create it+ account_id = "remotion-sa"+ display_name = "Remotion Service Account"+ description = var.remotion_version+}++# Bind the IAM role to the service account+resource "google_project_iam_member" "remotion_sa" {+ project = var.project_id+ role = google_project_iam_custom_role.remotion_sa.id+ member = "serviceAccount:${local.service-account-email}"+}++# Enable Cloud Run API+resource "google_project_service" "cloud_run" {+ project = var.project_id+ service = "run.googleapis.com"+}++# Enable Cloud Resource Manager+resource "google_project_service" "cloud_resource_manager" {+ project = var.project_id+ service = "cloudresourcemanager.googleapis.com"+}++# For tf state diagnosis, output the project ID+output "remotion_project_id" {+ value = var.project_id+}diff --git a/packages/cloudrun/gcpInstaller/tasks/generateEnv.mjs b/packages/cloudrun/gcpInstaller/tasks/generateEnv.mjsnew file mode 100644index 0000000000..41d7cf4ed3--- /dev/null+++ b/packages/cloudrun/gcpInstaller/tasks/generateEnv.mjs@@ -0,0 +1,104 @@+import { execSync } from "child_process";+import readline from "readline";+import { colorCode } from "../components/colorCodes.mjs";+import { checkEnvFile } from "../components/checkEnvFile.mjs";++export async function generateEnv(projectID) {+ /****************************************+ * Generate .env file+ ****************************************/+ await checkEnvFile();++ function deleteKeyPrompt() {+ return new Promise((resolve) => {+ const rl = readline.createInterface({+ input: process.stdin,+ output: process.stdout,+ });++ rl.question(+ `\n${colorCode.greenText}To delete one of these keys, type in the KEY_ID. Otherwise, press enter to continue. ${colorCode.blueText}`,+ async (answer) => {+ // reset terminal color+ rl.output.write(`${colorCode.resetText}`);++ if (answer.trim() === "") {+ rl.output.write(+ `${colorCode.blueText}<enter pressed>\n${colorCode.resetText}`+ );+ rl.close();+ return resolve(true);+ }++ rl.close();+ execSync(+ `gcloud iam service-accounts keys delete ${answer.trim()} --iam-account=remotion-sa@${projectID}.iam.gserviceaccount.com`,+ { stdio: "inherit" }+ );++ const result = await deleteKeyPrompt();++ resolve(result);+ }+ );+ });+ }++ execSync(+ `echo "\nThere is a limit of 10 keys per Service Account in GCP (not including the one managed by GCP itself).\n"`,+ {+ stdio: "inherit",+ }+ );++ execSync(+ `echo "You should delete any of these keys that are no longer in use for ${colorCode.blueText}remotion-sa@${projectID}.iam.gserviceaccount.com${colorCode.resetText}:\n"`,+ {+ stdio: "inherit",+ }+ );++ execSync(+ `gcloud iam service-accounts keys list --iam-account=remotion-sa@${projectID}.iam.gserviceaccount.com`,+ { stdio: "inherit" }+ );++ await deleteKeyPrompt();++ execSync(`echo "\nGenerating new Service Account key...\n"`, {+ stdio: "inherit",+ });++ // generate key.json file+ try {+ execSync(+ `gcloud iam service-accounts keys create key.json --iam-account=remotion-sa@${projectID}.iam.gserviceaccount.com`,+ { stdio: "inherit" }+ );+ } catch (e) {+ execSync(+ `echo "\n${colorCode.redBackground}Creation of new key failed, check if you have more than 10 keys already.${colorCode.resetText}\n\n"`,+ { stdio: "inherit" }+ );+ throw e;+ }++ // generate .env file+ execSync(+ `echo "REMOTION_GCP_PRIVATE_KEY=$(jq '.private_key' key.json)" >> .env && echo "REMOTION_GCP_CLIENT_EMAIL=$(jq '.client_email' key.json)" >> .env && echo "REMOTION_GCP_PROJECT_ID=${projectID}" >> .env`,+ { stdio: "inherit" }+ );++ // delete key.json file+ execSync("rm key.json", { stdio: "inherit" });++ execSync(+ `echo "\n${colorCode.greenText}key.json has been deleted from this virtual machine, and .env file is ready for download.${colorCode.resetText}"`,+ { stdio: "inherit" }+ );++ execSync(+ `echo "\n${colorCode.redText}To delete .env from this virtual machine after downloading, run${colorCode.resetText} rm .env"`,+ { stdio: "inherit" }+ );+}diff --git a/packages/cloudrun/gcpInstaller/tasks/setupGcpProject.mjs b/packages/cloudrun/gcpInstaller/tasks/setupGcpProject.mjsnew file mode 100644index 0000000000..d5f8c26caa--- /dev/null+++ b/packages/cloudrun/gcpInstaller/tasks/setupGcpProject.mjs@@ -0,0 +1,138 @@+import { execSync } from "child_process";+// Components+import { colorCode } from "../components/colorCodes.mjs";+import { remotionVersionPrompt } from "../components/remotionVersionPrompt.mjs";+import { checkTerraformStateFile } from "../components/checkTerraformStateFile.mjs";+import { generateEnvPrompt } from "../components/generateEnvPrompt.mjs";+import { terraformApplyPrompt } from "../components/terraformApplyPrompt.mjs";+// Tasks+import { generateEnv } from "./generateEnv.mjs";++export async function setupGcpProject(projectID) {+ checkTerraformStateFile(projectID);+ /****************************************+ * Prompt user for Remotion version+ ****************************************/+ const remotionVersion = await remotionVersionPrompt();++ /****************************************+ * Check if Remotion Service Account already exists+ ****************************************/+ execSync('echo "Checking if Remotion Service Account already exists..."', {+ stdio: "inherit",+ });++ const serviceAccountExists =+ execSync(+ `gcloud iam service-accounts list --filter="email:remotion-sa@${projectID}.iam.gserviceaccount.com" --project=${projectID}`,+ {+ stdio: ["inherit", "pipe", "pipe"],+ }+ )+ .toString()+ .trim().length > 0;++ if (serviceAccountExists) {+ execSync(+ `echo "${colorCode.blueText}remotion-sa@${projectID}.iam.gserviceaccount.com${colorCode.resetText} found, and does not need to be created.\n"`,+ {+ stdio: "inherit",+ }+ );+ } else {+ execSync(+ `echo "No service account found, ${colorCode.blueText}remotion-sa@${projectID}.iam.gserviceaccount.com${colorCode.resetText} will be created.\n"`,+ {+ stdio: "inherit",+ }+ );+ }++ /****************************************+ * Check if Remotion IAM Role already exists+ ****************************************/+ execSync('echo "Checking if Remotion IAM Role already exists..."', {+ stdio: "inherit",+ });++ let iamRoleExists = false;+ try {+ execSync(`gcloud iam roles describe RemotionSA --project=${projectID}`, {+ stdio: ["inherit", "pipe", "pipe"],+ })+ .toString()+ .trim();+ iamRoleExists = true;+ execSync(+ `echo "${colorCode.blueText}RemotionSA${colorCode.resetText} role found, and does not need to be created.\n"`,+ {+ stdio: "inherit",+ }+ );+ } catch {+ iamRoleExists = false;+ execSync(+ `echo "Role not found, ${colorCode.blueText}RemotionSA${colorCode.resetText} will be created.\n"`,+ {+ stdio: "inherit",+ }+ );+ }++ /****************************************+ * Terraform init, plan and apply. Will prompt user for confirmation before applying.+ ****************************************/++ console.log(+ `\n\n${colorCode.greenBackground} Running Terraform ${colorCode.resetText}`+ );+ const terraformVariables = `-var="remotion_version=${remotionVersion}" -var="project_id=${projectID}" -var="service_account_exists=${serviceAccountExists}"`;++ execSync("terraform init", { stdio: "inherit" });++ if (iamRoleExists) {+ // If the role already exists, import the resource so that the permissions can be updated in place++ // If tfstate file exists, remove the role resource from state so that it can be imported fresh+ try {+ execSync("terraform state list", { stdio: "pipe" });+ execSync(+ `terraform state rm google_project_iam_custom_role.remotion_sa`,+ {+ stdio: "inherit",+ }+ );+ } catch {}++ execSync(+ `terraform import ${terraformVariables} google_project_iam_custom_role.remotion_sa projects/${projectID}/roles/RemotionSA`,+ { stdio: "inherit" }+ );+ }++ execSync(`terraform plan ${terraformVariables} -out=remotion.tfplan`, {+ stdio: "inherit",+ });++ // After the plan is complete, prompt the user to apply the plan or not+ const applyPlan = await terraformApplyPrompt();++ if (applyPlan) {+ execSync("terraform apply remotion.tfplan", { stdio: "inherit" });+ // After the resources are created, prompt the user to generate the .env file or not+ const generateEnvFile = await generateEnvPrompt();+ if (generateEnvFile) {+ await generateEnv(projectID);+ } else {+ console.log("No .env file generated.");+ }+ } else {+ console.log("Plan not applied, no changes made.");+ const generateEnvFile = await generateEnvPrompt();+ if (generateEnvFile) {+ await generateEnv(projectID);+ } else {+ console.log("No .env file generated.");+ }+ }+}diff --git a/packages/cloudrun/gcpInstaller/tasks/updateRemotion.mjs b/packages/cloudrun/gcpInstaller/tasks/updateRemotion.mjsnew file mode 100644index 0000000000..24dc873681--- /dev/null+++ b/packages/cloudrun/gcpInstaller/tasks/updateRemotion.mjs@@ -0,0 +1,76 @@+import { execSync } from "child_process";+// Components+import { colorCode } from "../components/colorCodes.mjs";+import { remotionVersionPrompt } from "../components/remotionVersionPrompt.mjs";+import { terraformApplyPrompt } from "../components/terraformApplyPrompt.mjs";+import { checkTerraformStateFile } from "../components/checkTerraformStateFile.mjs";++export async function updateRemotion(projectID) {+ checkTerraformStateFile(projectID);++ /****************************************+ * Check the existing remotion version+ ****************************************/++ const deployedVersion = execSync(+ `gcloud iam service-accounts describe remotion-sa@${projectID}.iam.gserviceaccount.com | grep "description:" | awk '{print $2}'`,+ {+ stdio: ["inherit", "pipe", "pipe"],+ }+ )+ .toString()+ .trim();++ execSync(+ `echo "For project ${colorCode.blueText}${projectID}${colorCode.resetText}, Remotion version ${colorCode.blueText}${deployedVersion}${colorCode.resetText} is deployed.\n"`,+ {+ stdio: "inherit",+ }+ );++ const remotionVersion = await remotionVersionPrompt();++ /****************************************+ * Terraform init, plan and apply. Will prompt user for confirmation before applying.+ ****************************************/++ console.log(+ `\n\n${colorCode.greenBackground} Running Terraform ${colorCode.resetText}`+ );+ const terraformVariables = `-var="remotion_version=${remotionVersion}" -var="project_id=${projectID}" -var="service_account_exists=${true}"`;++ execSync("terraform init", { stdio: "inherit" });++ // If tfstate file exists, remove the role resource from state so that it can be imported fresh+ try {+ execSync("terraform state list", { stdio: "pipe" });+ execSync(`terraform state rm google_project_iam_custom_role.remotion_sa`, {+ stdio: "inherit",+ });+ } catch {}++ execSync(+ `terraform import ${terraformVariables} google_project_iam_custom_role.remotion_sa projects/${projectID}/roles/RemotionSA`,+ { stdio: "inherit" }+ );++ execSync(+ `terraform import ${terraformVariables} google_service_account.remotion_sa projects/${projectID}/serviceAccounts/remotion-sa@${projectID}.iam.gserviceaccount.com`,+ { stdio: "inherit" }+ );++ execSync(`terraform plan ${terraformVariables} -out=remotion.tfplan`, {+ stdio: "inherit",+ });++ // After the plan is complete, prompt the user to apply the plan or not+ const applyPlan = await terraformApplyPrompt();++ if (applyPlan) {+ execSync("terraform apply remotion.tfplan", { stdio: "inherit" });+ } else {+ console.log(+ "Plan not applied, deployed Remotion version remains unchanged."+ );+ }+}diff --git a/packages/cloudrun/install.mjs b/packages/cloudrun/install.mjsdeleted file mode 100644index e20bdedf4e..0000000000--- a/packages/cloudrun/install.mjs+++ /dev/null@@ -1,597 +0,0 @@-// this will be executed with node-import {execSync} from 'child_process';-import {existsSync, readFileSync} from 'fs';-import readline from 'readline';--/****************************************- * Text colours codes- ****************************************/-const resetTextColor = '\u001b[0m';-const greenTextColor = `${resetTextColor}\u001b[32;1m`;-const blueTextColor = `${resetTextColor}\u001b[34;1m`;-const redTextColor = `${resetTextColor}\u001b[31;1m`;-const redBackground = `${resetTextColor}\u001b[41;1m`;-const greenBackground = `${resetTextColor}\u001b[42;1m`;--/****************************************- * Splash screen for Remotion Cloud Run- ****************************************/-execSync(- `echo "\n\n${greenBackground} "`,- {- stdio: 'inherit',- }-);-execSync('echo " GCP project setup for Remotion Cloud Run "', {- stdio: 'inherit',-});-execSync(- `echo " \n\n${resetTextColor}"`,- {stdio: 'inherit'}-);--/****************************************- * Set project ID for Terraform and gcloud commands- ****************************************/-execSync(`echo "Retrieving current Project ID..."`, {- stdio: 'inherit',-});--const projectID = execSync('gcloud config get-value project', {- stdio: ['inherit', 'pipe', 'pipe'],-})- .toString()- .trim();--execSync(- `echo "Project set to ${blueTextColor}${projectID}${resetTextColor}\n"`,- {- stdio: 'inherit',- }-);--/****************************************- * Check if user is configuring GCP Project, or just needs to generate .env file- ****************************************/-function taskPrompt() {- return new Promise((resolve) => {- const rl = readline.createInterface({- input: process.stdin,- output: process.stdout,- });-- rl.question(- `What would you like to do?\n[1] Setup the GCP project ${projectID} as a Remotion Cloud Run environment.\n[2] ${projectID} is already set up for Remotion, update to a newer Remotion version.\n[3] ${projectID} is already set up for Remotion, generate a new .env file or manage keys for the Remotion Service Account.\n${blueTextColor}`,- async (answer) => {- // reset terminal color- rl.output.write(`\n${resetTextColor}`);-- if (answer.trim() === '1') {- rl.output.write(- `${blueTextColor}<Terraform selected>\n\n${resetTextColor}`- );- rl.close();- return resolve('runTerraform');- }-- if (answer.trim() === '2') {- rl.output.write(- `${blueTextColor}<Update Remotion selected>\n\n${resetTextColor}`- );- rl.close();- return resolve('updateRemotion');- }-- if (answer.trim() === '3') {- rl.output.write(- `${blueTextColor}<.env creation selected>\n\n${resetTextColor}`- );- rl.close();- return resolve('generateEnv');- }-- rl.close();- execSync(- `echo "${redTextColor}Invalid selection. Please enter 1, 2 or 3.\n${resetTextColor}"`,- {- stdio: 'inherit',- }- );-- const result = await taskPrompt();-- resolve(result);- }- );- });-}--const selection = await taskPrompt();--switch (selection) {- case 'runTerraform':- await runTerraform();- break;-- case 'updateRemotion':- await updateRemotion();- break;-- case 'generateEnv':- await generateEnv();- break;-- default:- break;-}--function envPrompt() {- return new Promise((resolve) => {- const rl = readline.createInterface({- input: process.stdin,- output: process.stdout,- });-- rl.question(- `\n${greenTextColor}Do you want to generate the .env file for your code base? ${blueTextColor}`,- async (answer) => {- // reset terminal color- rl.output.write(`${resetTextColor}`);- rl.close();-- if (['yes', 'y'].indexOf(answer.trim().toLowerCase()) >= 0)- return resolve(true);-- if (['no', 'n'].indexOf(answer.trim().toLowerCase()) >= 0)- return resolve(false);-- console.log('Invalid response.');- const result = await envPrompt();-- resolve(result);- }- );- });-}--function checkTerraformStateFile() {- /****************************************- * Check for existing Terraform State- ****************************************/-- if (existsSync('terraform.tfstate')) {- execSync(- 'echo "Terraform State file exists. Checking it is for the current Remotion project...\n"',- {stdio: 'inherit'}- );-- const tfstate = JSON.parse(readFileSync('terraform.tfstate', 'utf-8'));-- const tfstateProject = tfstate.outputs?.remotion_project_id?.value;-- if (tfstateProject === undefined) {- execSync(- `echo "${redTextColor}Terraform state file is not from a Remotion project.\nChange directory, or delete all existing terraform files within the current directory, before trying again.\nTo delete all terraform files, run: ${resetTextColor}rm -rf .terraform terraform.tfstate terraform.tfstate.backup .terraform.lock.hcl terraform.tfstate.*.backup"`,- {stdio: 'inherit'}- );- process.exit(1);- }-- if (tfstateProject === projectID) {- execSync(- `echo "${greenTextColor}Terraform state file is for the current Remotion project - ${projectID}. Continuing...${resetTextColor}\n"`,- {stdio: 'inherit'}- );- } else {- execSync(- `echo "${redTextColor}Terraform state file is for project ${redBackground}${tfstateProject}${redTextColor}.\nThe current project is ${redBackground}${projectID}${redTextColor}.\nChange directory, or delete all existing terraform files within the current directory, before trying again.${resetTextColor}"`,- {stdio: 'inherit'}- );- process.exit(1);- }- }-}--function versionPrompt() {- return new Promise((resolve) => {- // regex to ensure remotionVersion is in semver format- const semverRegex = new RegExp(- /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,- 'i'- );-- const rl = readline.createInterface({- input: process.stdin,- output: process.stdout,- });-- rl.question(- `What version of Remotion do you want to use (format: 1.0.0)? ${blueTextColor}`,- async (answer) => {- rl.write(`\n${resetTextColor}`);- rl.close();-- let fileError = false;- if (semverRegex.test(answer.trim())) {- try {- execSync(- `gcloud storage ls gs://remotion-sa/${answer.trim()}/sa-permissions.json`,- {stdio: 'inherit'}- );- return resolve(answer.trim());- } catch {- fileError = true;- }- }-- if (fileError) {- console.log(- `${redTextColor}Cannot find permissions file that matches version ${answer.trim()}.\n${resetTextColor}`- );- } else {- console.log(- `${redTextColor}${answer.trim()} is not a valid semver version number.\n${resetTextColor}`- );- }-- const result = await versionPrompt();-- resolve(result);- }- );- });-}--async function runTerraform() {- await checkTerraformStateFile();- /****************************************- * Prompt user for Remotion version- ****************************************/-- const remotionVersion = await versionPrompt();-- /****************************************- * Check if Remotion Service Account already exists- ****************************************/-- execSync('echo "Checking if Remotion Service Account already exists..."', {- stdio: 'inherit',- });-- const serviceAccountExists =- execSync(- `gcloud iam service-accounts list --filter="email:remotion-sa@${projectID}.iam.gserviceaccount.com" --project=${projectID}`,- {- stdio: ['inherit', 'pipe', 'pipe'],- }- )- .toString()- .trim().length > 0;-- if (serviceAccountExists) {- execSync(- `echo "${blueTextColor}remotion-sa@${projectID}.iam.gserviceaccount.com${resetTextColor} found, and does not need to be created.\n"`,- {- stdio: 'inherit',- }- );- } else {- execSync(- `echo "No service account found, ${blueTextColor}remotion-sa@${projectID}.iam.gserviceaccount.com${resetTextColor} will be created.\n"`,- {- stdio: 'inherit',- }- );- }-- /****************************************- * Check if Remotion IAM Role already exists- ****************************************/-- execSync('echo "Checking if Remotion IAM Role already exists..."', {- stdio: 'inherit',- });-- let iamRoleExists = false;- try {- execSync(`gcloud iam roles describe RemotionSA --project=${projectID}`, {- stdio: ['inherit', 'pipe', 'pipe'],- })- .toString()- .trim();- iamRoleExists = true;- execSync(- `echo "${blueTextColor}RemotionSA${resetTextColor} role found, and does not need to be created.\n"`,- {- stdio: 'inherit',- }- );- } catch {- iamRoleExists = false;- execSync(- `echo "Role not found, ${blueTextColor}RemotionSA${resetTextColor} will be created.\n"`,- {- stdio: 'inherit',- }- );- }-- /****************************************- * Terraform init, plan and apply. Will prompt user for confirmation before applying.- ****************************************/-- console.log(- `\n\n${greenBackground} Running Terraform ${resetTextColor}`- );- const terraformVariables = `-var="remotion_version=${remotionVersion}" -var="project_id=${projectID}" -var="service_account_exists=${serviceAccountExists}"`;-- execSync('terraform init', {stdio: 'inherit'});-- if (iamRoleExists) {- // If the role already exists, import the resource so that the permissions can be updated in place-- // If tfstate file exists, remove the role resource from state so that it can be imported fresh- try {- execSync('terraform state list', {stdio: 'pipe'});- execSync(- `terraform state rm google_project_iam_custom_role.remotion_sa`,- {- stdio: 'inherit',- }- );- } catch {}-- execSync(- `terraform import ${terraformVariables} google_project_iam_custom_role.remotion_sa projects/${projectID}/roles/RemotionSA`,- {stdio: 'inherit'}- );- }-- execSync(`terraform plan ${terraformVariables} -out=remotion.tfplan`, {- stdio: 'inherit',- });-- // After the plan is complete, prompt the user to apply the plan or not- function applyPrompt() {- return new Promise((resolve) => {- const rl = readline.createInterface({- input: process.stdin,- output: process.stdout,- });-- rl.question(- `\n${greenTextColor}Do you want to apply the above plan? ${blueTextColor}`,- async (answer) => {- // reset terminal color- rl.output.write(resetTextColor);- rl.close();-- if (['yes', 'y'].indexOf(answer.trim().toLowerCase()) >= 0)- return resolve(true);-- if (['no', 'n'].indexOf(answer.trim().toLowerCase()) >= 0)- return resolve(false);-- console.log('Invalid response.');- const result = await applyPrompt();-- resolve(result);- }- );- });- }-- const applyPlan = await applyPrompt();-- if (applyPlan) {- execSync('terraform apply remotion.tfplan', {stdio: 'inherit'});- // After the resources are created, prompt the user to generate the .env file or not- const generateEnvPrompt = await envPrompt();- if (generateEnvPrompt) {- await generateEnv();- } else {- console.log('No .env file generated.');- }- } else {- console.log('Plan not applied, no changes made.');- const generateEnvPrompt = await envPrompt();- if (generateEnvPrompt) {- await generateEnv();- } else {- console.log('No .env file generated.');- }- }-}--async function updateRemotion() {- await checkTerraformStateFile();-- /****************************************- * Check the existing remotion version- ****************************************/-- const deployedVersion = execSync(- `gcloud iam service-accounts describe remotion-sa@${projectID}.iam.gserviceaccount.com | grep "description:" | awk '{print $2}'`,- {- stdio: ['inherit', 'pipe', 'pipe'],- }- )- .toString()- .trim();-- execSync(- `echo "For project ${blueTextColor}${projectID}${resetTextColor}, Remotion version ${blueTextColor}${deployedVersion}${resetTextColor} is deployed.\n"`,- {- stdio: 'inherit',- }- );-- const remotionVersion = await versionPrompt();-- /****************************************- * Terraform init, plan and apply. Will prompt user for confirmation before applying.- ****************************************/-- console.log(- `\n\n${greenBackground} Running Terraform ${resetTextColor}`- );- const terraformVariables = `-var="remotion_version=${remotionVersion}" -var="project_id=${projectID}" -var="service_account_exists=${true}"`;-- execSync('terraform init', {stdio: 'inherit'});-- // If tfstate file exists, remove the role resource from state so that it can be imported fresh- try {- execSync('terraform state list', {stdio: 'pipe'});- execSync(`terraform state rm google_project_iam_custom_role.remotion_sa`, {- stdio: 'inherit',- });- } catch {}-- execSync(- `terraform import ${terraformVariables} google_project_iam_custom_role.remotion_sa projects/${projectID}/roles/RemotionSA`,- {stdio: 'inherit'}- );-- execSync(`terraform plan ${terraformVariables} -out=remotion.tfplan`, {- stdio: 'inherit',- });-- // After the plan is complete, prompt the user to apply the plan or not- function applyPrompt() {- return new Promise((resolve) => {- const rl = readline.createInterface({- input: process.stdin,- output: process.stdout,- });-- rl.question(- `\n${greenTextColor}Do you want to apply the above plan? ${blueTextColor}`,- async (answer) => {- // reset terminal color- rl.output.write(resetTextColor);- rl.close();-- if (['yes', 'y'].indexOf(answer.trim().toLowerCase()) >= 0)- return resolve(true);-- if (['no', 'n'].indexOf(answer.trim().toLowerCase()) >= 0)- return resolve(false);-- console.log('Invalid response.');- const result = await applyPrompt();-- resolve(result);- }- );- });- }-- const applyPlan = await applyPrompt();-- if (applyPlan) {- execSync('terraform apply remotion.tfplan', {stdio: 'inherit'});- } else {- console.log(- 'Plan not applied, deployed Remotion version remains unchanged.'- );- }-}--async function generateEnv() {- /****************************************- * Generate .env file- ****************************************/-- function deleteKeyPrompt() {- return new Promise((resolve) => {- const rl = readline.createInterface({- input: process.stdin,- output: process.stdout,- });-- rl.question(- `\n${greenTextColor}To delete one of these keys, type in the KEY_ID. Otherwise, press enter to continue. ${blueTextColor}`,- async (answer) => {- // reset terminal color- rl.output.write(`${resetTextColor}`);-- if (answer.trim() === '') {- rl.output.write(- `${blueTextColor}<enter pressed>\n${resetTextColor}`- );- rl.close();- return resolve(true);- }-- rl.close();- execSync(- `gcloud iam service-accounts keys delete ${answer.trim()} --iam-account=remotion-sa@${projectID}.iam.gserviceaccount.com`,- {stdio: 'inherit'}- );-- const result = await deleteKeyPrompt();-- resolve(result);- }- );- });- }-- execSync(- `echo "\nThere is a limit of 10 keys per Service Account in GCP (not including the one managed by GCP itself).\n"`,- {- stdio: 'inherit',- }- );-- execSync(- `echo "You should delete any of these keys that are no longer in use for ${blueTextColor}remotion-sa@${projectID}.iam.gserviceaccount.com${resetTextColor}:\n"`,- {- stdio: 'inherit',- }- );-- execSync(- `gcloud iam service-accounts keys list --iam-account=remotion-sa@${projectID}.iam.gserviceaccount.com`,- {stdio: 'inherit'}- );-- await deleteKeyPrompt();-- execSync(`echo "\nGenerating new Service Account key...\n"`, {- stdio: 'inherit',- });-- // generate key.json file- try {- execSync(- `gcloud iam service-accounts keys create key.json --iam-account=remotion-sa@${projectID}.iam.gserviceaccount.com`,- {stdio: 'inherit'}- );- } catch (e) {- execSync(- `echo "\n${redBackground}Creation of new key failed, check if you have more than 10 keys already.${resetTextColor}\n\n"`,- {stdio: 'inherit'}- );- throw e;- }-- // generate .env file- execSync(- `echo "REMOTION_GCP_PRIVATE_KEY=$(jq '.private_key' key.json)" >> .env && echo "REMOTION_GCP_CLIENT_EMAIL=$(jq '.client_email' key.json)" >> .env && echo "REMOTION_GCP_PROJECT_ID=${projectID}" >> .env`,- {stdio: 'inherit'}- );-- // delete key.json file- execSync('rm key.json', {stdio: 'inherit'});-- execSync(- `echo "\n${greenTextColor}key.json has been deleted from this virtual machine, and .env file is ready for download.${resetTextColor}"`,- {stdio: 'inherit'}- );-- execSync(- `echo "\n${redTextColor}To delete .env from this virtual machine after downloading, run${resetTextColor} rm .env"`,- {stdio: 'inherit'}- );-}