Skip to content

Commit

Permalink
🎉: Add feature to send deployment logs directly to Slack
Browse files Browse the repository at this point in the history
  • Loading branch information
arddluma committed Aug 4, 2023
1 parent 102d19c commit 4d5b0d3
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 24 deletions.
Binary file modified .github/images/build-failed.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added .github/images/old-build-failed.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Generate API Token go to https://dash.cloudflare.com/profile/api-tokens
## Usage
```yml
- name: Await CF Pages and send Slack notification
uses: arddluma/cloudflare-pages-slack-notification@v3.1
uses: arddluma/cloudflare-pages-slack-notification@v4
with:
# Uncomment these two lines if you wish to use the Global API Key (Not recommended!)
# accountEmail: ${{ secrets.CF_ACCOUNT_EMAIL }}
Expand Down Expand Up @@ -41,7 +41,7 @@ jobs:
- uses: actions/checkout@v3
- name: Await CF Pages and send Slack notification
id: cf-pages
uses: arddluma/cloudflare-pages-slack-notification@v3.1
uses: arddluma/cloudflare-pages-slack-notification@v4
with:
# Uncomment these two lines if you wish to use the Global API Key (Not recommended!)
# accountEmail: ${{ secrets.CF_ACCOUNT_EMAIL }}
Expand Down
57 changes: 47 additions & 10 deletions dist/action.js
Original file line number Diff line number Diff line change
Expand Up @@ -12767,6 +12767,7 @@ var waiting = true;
var ghDeployment;
var markedAsInProgress = false;
async function run() {
var _a2, _b, _c;
const accountEmail = core.getInput("accountEmail", { required: false, trimWhitespace: true });
const apiKey = core.getInput("apiKey", { required: false, trimWhitespace: true });
const apiToken = core.getInput("apiToken", { required: false, trimWhitespace: true });
Expand All @@ -12776,6 +12777,8 @@ async function run() {
const commitHash = core.getInput("commitHash", { required: false, trimWhitespace: true });
const slackWebHook = core.getInput("slackWebHook", { required: false, trimWhitespace: true });
const slack = esm_default(slackWebHook);
const commitUrl = ((_b = (_a2 = import_utils.context.payload) == null ? void 0 : _a2.head_commit) == null ? void 0 : _b.url) || "";
const actor = ((_c = import_utils.context) == null ? void 0 : _c.actor) || "";
if (!validateAuthInputs(apiToken, accountEmail, apiKey)) {
return;
}
Expand Down Expand Up @@ -12806,20 +12809,54 @@ async function run() {
}
if (latestStage.status === "failed" || latestStage.status === "failure") {
waiting = false;
slack.send(`:x: CloudFlare Pages \`${latestStage.name}\` pipeline for project *${project}* \`FAILED\`!
if (slackWebHook) {
const logs = await getCloudflareLogs(authHeaders, accountId, project, deployment.id);
slack.send(`:x: CloudFlare Pages \`${latestStage.name}\` pipeline for project *${project}* \`FAILED\`!
Environment: *${deployment.environment}*
Commit: ${import_utils.context.payload.head_commit.url}
Actor: *${import_utils.context.actor}*
Commit: ${commitUrl}
Actor: *${actor}*
Deployment ID: *${deployment.id}*
Checkout <https://dash.cloudflare.com?to=/${accountId}/pages/view/${deployment.project_name}/${deployment.id}|build logs>`).then(() => {
console.log(`Slack message for ${latestStage.name} failed pipeline sent!`);
}).catch((err) => {
console.error(err);
});
Deployment Logs: ${logs}
`).then(() => {
console.log(`Slack message for ${latestStage.name} failed pipeline sent!`);
}).catch((err) => {
console.error(err);
});
}
core.setFailed(`Deployment failed on step: ${latestStage.name}!`);
await updateDeployment(token, deployment, "failure");
return;
}
async function getCloudflareLogs(authHeaders2, accountId2, project2, deploymentId) {
var _a3;
try {
const res = await fetch(`https://api.cloudflare.com/client/v4/accounts/${accountId2}/pages/projects/${project2}/deployments/${deploymentId}/history/logs`, {
headers: { ...authHeaders2 }
});
if (!res.ok) {
console.error(`Failed to fetch Cloudflare logs - Status code: ${res.status} (${res.statusText})`);
return "";
}
const body = await res.json();
if (Array.isArray((_a3 = body.result) == null ? void 0 : _a3.data) && body.result.data.length > 0) {
const logs = body.result.data.map((log) => {
return {
line: log.line
};
});
const last20Logs = logs.slice(-20);
const formattedLogs = last20Logs.map((log) => {
return `${log.line}`;
});
return "```" + formattedLogs.join("\n") + "\n```";
} else {
return "";
}
} catch (error2) {
console.error(`Failed to fetch Cloudflare logs: ${error2.message}`);
return "";
}
}
if (latestStage.name === "deploy" && ["success", "failed"].includes(latestStage.status)) {
waiting = false;
const aliasUrl = deployment.aliases && deployment.aliases.length > 0 ? deployment.aliases[0] : deployment.url;
Expand All @@ -12831,8 +12868,8 @@ Checkout <https://dash.cloudflare.com?to=/${accountId}/pages/view/${deployment.p
if (deployment.latest_stage.status === "success" && true) {
slack.send(`:white_check_mark: CloudFlare Pages \`Deployment\` pipeline for project *${project}* \`SUCCEEDED\`!
Environment: *${deployment.environment}*
Commit: ${import_utils.context.payload.head_commit.url}
Actor: *${import_utils.context.actor}*
Commit: ${commitUrl}
Actor: *${actor}*
Deployment ID: *${deployment.id}*
Alias URL: ${aliasUrl}
Deployment URL: ${deployment.url}
Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "cloudflare-pages-slack-notification",
"version": "3.0.1",
"version": "4.0.0",
"description": "Wait for a Cloudflare Pages build to finish and send Slack notification",
"main": "index.js",
"keywords": [],
Expand Down
55 changes: 48 additions & 7 deletions src/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ export default async function run() {
const commitHash = core.getInput('commitHash', { required: false, trimWhitespace: true });
const slackWebHook = core.getInput('slackWebHook', { required: false, trimWhitespace: true });
const slack = SlackNotify(slackWebHook);
const commitUrl = context.payload?.head_commit?.url || '';
const actor = context?.actor || '';

// Validate we have either token or both email + key
if (!validateAuthInputs(apiToken, accountEmail, apiKey)) {
Expand Down Expand Up @@ -64,16 +66,55 @@ export default async function run() {

if (latestStage.status === 'failed' || latestStage.status === 'failure') {
waiting = false;
slack.send(`:x: CloudFlare Pages \`${latestStage.name}\` pipeline for project *${project}* \`FAILED\`!\nEnvironment: *${deployment.environment}*\nCommit: ${context.payload.head_commit.url}\nActor: *${context.actor}*\nDeployment ID: *${deployment.id}*\nCheckout <https://dash.cloudflare.com?to=/${accountId}/pages/view/${deployment.project_name}/${deployment.id}|build logs>`).then(() => {
console.log(`Slack message for ${latestStage.name} failed pipeline sent!`);
}).catch((err) => {
console.error(err);
});

if (slackWebHook) {
const logs = await getCloudflareLogs(authHeaders, accountId, project, deployment.id);
slack.send(`:x: CloudFlare Pages \`${latestStage.name}\` pipeline for project *${project}* \`FAILED\`!\nEnvironment: *${deployment.environment}*\nCommit: ${commitUrl}\nActor: *${actor}*\nDeployment ID: *${deployment.id}*\nDeployment Logs: ${logs}\n`).then(() => {
console.log(`Slack message for ${latestStage.name} failed pipeline sent!`);
}).catch((err) => {
console.error(err);
});
}
core.setFailed(`Deployment failed on step: ${latestStage.name}!`);
await updateDeployment(token, deployment, 'failure');
return;
}
async function getCloudflareLogs(authHeaders: AuthHeaders, accountId: string, project: string, deploymentId: string): Promise<string> {
try {
const res: Response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${accountId}/pages/projects/${project}/deployments/${deploymentId}/history/logs`, {
headers: { ...authHeaders },
});

if (!res.ok) {
console.error(`Failed to fetch Cloudflare logs - Status code: ${res.status} (${res.statusText})`);
return '';
}

const body = await res.json();

if (Array.isArray(body.result?.data) && body.result.data.length > 0) {
const logs = body.result.data.map((log: any) => {
return {
line: log.line,
};
});

const last20Logs = logs.slice(-20);

const formattedLogs = last20Logs.map((log) => {
return `${log.line}`;
});

return '```' + formattedLogs.join('\n') + '\n```';
} else {
return '';
}
} catch (error) {
console.error(`Failed to fetch Cloudflare logs: ${error.message}`);
return '';
}
}

if (latestStage.name === 'deploy' && ['success', 'failed'].includes(latestStage.status)) {
waiting = false;

Expand All @@ -87,7 +128,7 @@ export default async function run() {
core.setOutput('success', deployment.latest_stage.status === 'success' ? true : false);

if (deployment.latest_stage.status === 'success' && true) {
slack.send(`:white_check_mark: CloudFlare Pages \`Deployment\` pipeline for project *${project}* \`SUCCEEDED\`!\nEnvironment: *${deployment.environment}*\nCommit: ${context.payload.head_commit.url}\nActor: *${context.actor}*\nDeployment ID: *${deployment.id}*\nAlias URL: ${aliasUrl}\nDeployment URL: ${deployment.url}\nCheckout <https://dash.cloudflare.com?to=/${accountId}/pages/view/${deployment.project_name}/${deployment.id}|build logs>`).then(() => {
slack.send(`:white_check_mark: CloudFlare Pages \`Deployment\` pipeline for project *${project}* \`SUCCEEDED\`!\nEnvironment: *${deployment.environment}*\nCommit: ${commitUrl}\nActor: *${actor}*\nDeployment ID: *${deployment.id}*\nAlias URL: ${aliasUrl}\nDeployment URL: ${deployment.url}\nCheckout <https://dash.cloudflare.com?to=/${accountId}/pages/view/${deployment.project_name}/${deployment.id}|build logs>`).then(() => {
console.log('Slack message for DEPLOYMENT succedded pipeline sent!');
}).catch((err) => {
console.error(err);
Expand Down Expand Up @@ -211,4 +252,4 @@ try {
core.setFailed(e);
// @ts-ignore
console.error(e.message + '\n' + e.stack);
}
}

0 comments on commit 4d5b0d3

Please sign in to comment.