Skip to content

Instantly share code, notes, and snippets.

@shanonplace
Last active April 10, 2025 15:45
Show Gist options
  • Save shanonplace/12b6cccaa76b4a3287072c57cc35d83b to your computer and use it in GitHub Desktop.
Save shanonplace/12b6cccaa76b4a3287072c57cc35d83b to your computer and use it in GitHub Desktop.
Example script to copy a workflow definition from one environment to another in Contentful.
import * as dotenv from "dotenv";
import fetch from "node-fetch";
dotenv.config();
const workflowId = "3THnDj08TlJBoAM5oJorrrrfWn"; //These three could be .env file strings or cli params
const originEnvironment = "Workflow-Test";
const destinationEnvironment = "master";
//get a workflow definition from the origin environment
const workflowJson = await getWorkflowDefinition(workflowId, originEnvironment);
console.log("copying workflow ", JSON.stringify(workflowJson, null, 2));
//clear out the sys and id fields from the original workflow definition, as they cannot be included in a create
delete workflowJson.sys;
workflowJson.steps.forEach((s) => {
delete s.id;
});
//now create a new workflow in the destination environment
const createResponse = await createWorkflow(
workflowJson,
destinationEnvironment
).catch((e) => {
console.log("error is ", JSON.stringify(e));
});
console.log("Workflow Created! ", JSON.stringify(createResponse, null, 2));
//***********functions***************//
//get the full workflow definition to get a list of steps ids
async function getWorkflowDefinition(workflowId, environment) {
const token = `Bearer ${process.env.CMA_TOKEN}`;
const workflowFetchUrl = `https://api.contentful.com/spaces/${process.env.SPACE_ID}/environments/${environment}/workflow_definitions/${workflowId}`;
const workflowRes = await fetch(workflowFetchUrl, {
headers: {
Authorization: token,
},
});
const workflow = await workflowRes.json();
return workflow;
}
//async function to create workflow
async function createWorkflow(workflowJson, environment) {
const token = `Bearer ${process.env.CMA_TOKEN}`;
const workflowCreateUrl = `https://api.contentful.com/spaces/${process.env.SPACE_ID}/environments/${environment}/workflow_definitions`;
const workflowRes = await fetch(workflowCreateUrl, {
headers: {
"Authorization": token,
"Content-Type": "application/vnd.contentful.management.v1+json",
"Accept": "application/json, text/plain, */*",
},
method: "POST",
body: JSON.stringify(workflowJson),
});
const workflow = await workflowRes.json();
return workflow;
}
@shanonplace
Copy link
Author

Uses a .env file with the following format:

CMA_TOKEN="your-auth-token"
SPACE_ID="your-space-id"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment