Sub topic 13
Running setup and cleanup with pre and post
This chapter covers the pre and post lifecycle scripts of JavaScript actions. It assumes you can write a JavaScript action with @actions/core, read action.yml metadata, and bundle dependencies with a tool such as @vercel/ncc. It also assumes you know how if: conditions work in workflow steps.
Why an action needs more than one entry point
Most actions do all their work in main. Some actions need to do something before the job's other steps run, or after they finish. Examples:
- Start a cache server or a background service, and stop it at the end of the job.
- Create a temporary directory or credentials file, and delete it afterward.
- Upload logs or metrics whether the job succeeded or not.
You could ask users to add a cleanup step by hand. They would forget it, and it would not run after a failure unless they wrote if: always(). The pre and post keys in action.yml move this responsibility into the action.
The lifecycle
An action can have up to three scripts. The runner calls them at different points in the job.
| Script | Key | Runs | Default condition |
|---|---|---|---|
| Setup | `pre` | At the start of the job, before any regular step | `pre-if: always()` |
| Main | `main` | At the action's position in the step list | The step's own `if:` |
| Cleanup | `post` | At the end of the job, after all regular steps | `post-if: always()` |
Two ordering rules matter in practice:
- All
prescripts run first, in the order the actions appear in the job. Then the regular steps run. Then allpostscripts run in reverse order, so the last action to be set up is the first to be cleaned up. preruns beforeactions/checkout. Yourprescript cannot read the repository workspace, because it is not there yet.
Declaring pre and post in action.yml
The runs block takes pre, pre-if, post, and post-if next to main. This example creates a scratch directory before the job, lets a step write to it, and removes it afterward.
name: 'Scratch Directory'
description: 'Create a scratch directory before the job and remove it after the job'
inputs:
keep:
description: 'Set to true to skip cleanup'
required: false
default: 'false'
outputs:
dir:
description: 'Path to the scratch directory'
runs:
using: 'node20'
pre: 'setup.js'
main: 'main.js'
post: 'cleanup.js'
post-if: always()Each script is a separate file that the runner starts as its own Node process. They do not share memory, so a variable set in setup.js does not exist in main.js. This is the most common mistake with lifecycle scripts, and the next section shows the fix.
Passing data between scripts with state
The toolkit gives the three scripts a small shared store. core.saveState(name, value) writes a value, and core.getState(name) reads it in a later script of the same action in the same job. Under the hood, saveState appends to the file named by GITHUB_STATE. The runner then exposes each saved value to later scripts as an environment variable named STATE_<name>.
Here is the setup script:
const core = require('@actions/core');
const fs = require('fs');
const os = require('os');
const path = require('path');
try {
const base = process.env.RUNNER_TEMP || os.tmpdir();
const dir = fs.mkdtempSync(path.join(base, 'scratch-'));
core.saveState('scratchDir', dir);
core.info(`Created scratch directory ${dir}`);
} catch (error) {
core.setFailed(error.message);
}The main script reads the state back and exposes the path as an output:
const core = require('@actions/core');
const fs = require('fs');
const path = require('path');
try {
const dir = core.getState('scratchDir');
if (!dir) {
throw new Error('Scratch directory missing: the pre script did not run');
}
fs.writeFileSync(path.join(dir, 'note.txt'), `Written at ${new Date().toISOString()}\n`);
core.setOutput('dir', dir);
} catch (error) {
core.setFailed(error.message);
}The cleanup script reads the same state and removes the directory unless the keep input says otherwise. Inputs are available in pre and post just as they are in main.
const core = require('@actions/core');
const fs = require('fs');
try {
const dir = core.getState('scratchDir');
if (core.getInput('keep') === 'true') {
core.info(`Keeping ${dir}`);
} else if (dir) {
fs.rmSync(dir, { recursive: true, force: true });
core.info(`Removed ${dir}`);
}
} catch (error) {
core.setFailed(error.message);
}A single-file pattern
Some actions keep all logic in one file and branch on whether the script is running as main or post. They point both main and post at the same file. The first run saves a flag with core.saveState('isPost', 'true'). The second run sees the flag through core.getState('isPost') and takes the cleanup branch. This keeps the bundle small, but it hides the lifecycle inside conditionals. Separate files are easier to read and test, so prefer them unless bundle size matters.
Controlling when the scripts run
pre-if and post-if use the same expression syntax as a step's if:. They differ in which contexts are available.
pre-ifruns before any step, so thestepscontext is empty. You can usegithub,runner, andenv. For example,pre-if: runner.os == 'Linux'skips setup on other systems.post-ifcan inspect thestepscontext and the job status functions. These aresuccess(),failure(),cancelled(), andalways().
The default of always() for post-if means cleanup runs after a failed job as well. That is usually what you want. If you only want to upload diagnostics on failure, write post-if: failure().
Failure behavior
- A failing
prescript (non-zero exit, orcore.setFailed) marks the job as failed. The job's remaining steps do not run normally, but post scripts of actions that started still run when their condition allows. - A failing
postscript marks the job failed even if every step passed. Wrap risky cleanup intry/catchand callcore.warninginstead ofsetFailedwhen a failed cleanup should not fail the build. - If a runner is lost or the job is force-killed, no
postscript runs. Treat cleanup as best effort. For resources that cost money or hold locks, add a timeout or expiry on the resource itself.
Bundling and testing
Each script is an entry point, so each must be bundled. With ncc, build them separately and point action.yml at the outputs:
npx ncc build setup.js -o dist/setup
npx ncc build main.js -o dist/main
npx ncc build cleanup.js -o dist/cleanupThen set pre: 'dist/setup/index.js', main: 'dist/main/index.js', and post: 'dist/cleanup/index.js'. Commit the dist folder, as you do for any JavaScript action.
To test, use the local-path form from the earlier chapters. The workflow below runs the action, writes a file into the scratch directory from a later step, and shows that the directory is gone after the job.
name: Test scratch action
on: [push]
jobs:
scratch:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Use the scratch directory
id: scratch
uses: ./
- name: Read the file
run: cat "${{ steps.scratch.outputs.dir }}/note.txt"In the job log you will see the Pre Run entry near the top (it appears there even though the action is listed in the middle of the job) and a Post Run entry at the bottom. The post entry prints Removed ....
Note that the checkout step is listed first, but the pre script of the local action still runs before it. A local action's pre can only be found once the repository is checked out, so runners handle uses: ./ specially. For a local action, pre therefore runs after checkout. For an action referenced by owner/repo@ref, pre runs at the very start of the job.
Docker container actions
Container actions have equivalents: pre-entrypoint and post-entrypoint under runs, together with pre-if and post-if. Each starts a new container from the same image, with the entrypoint replaced by the script you name. State still travels through GITHUB_STATE, written the same way as GITHUB_OUTPUT: echo "name=value" >> "$GITHUB_STATE". Composite actions do not support pre or post.
Common mistakes
- Expecting variables to persist between scripts instead of using
saveState. - Assuming the repository is checked out in
pre. - Forgetting to bundle
setup.jsandcleanup.js, sorequire('@actions/core')fails at run time. - Using
postfor cleanup that must happen even when the runner crashes. - Throwing from
postfor a harmless cleanup error and failing a green build.
Exercise
An action's post script must upload a log file only when the job failed. Which key and value do you add to runs, and what does the script need in order to know which directory the log is in?
Show answer
Add post-if: failure() under runs, next to post. The script learns the log directory from state: the pre or main script calls core.saveState('logDir', dir), and the post script reads it with core.getState('logDir'). Variables from other scripts are not available, because each script runs in its own process.
Exercise
Two steps in one job both use your scratch action. In what order do the two post scripts run, and does the second invocation see the first one's saved scratchDir?
Show answer
The post scripts run in reverse order of the steps, so the second invocation's cleanup runs first. State is scoped to each invocation, so each one sees only the scratchDir that its own pre script saved.