How to Define Reusable Commands in CircleCI
A top-level commands: block bundles a sequence of steps behind a name you can invoke from any job, with parameters for the bits that change.
Declare a command under commands: with optional parameters:, then call it as a step by name. Pass values with the same with:-style mapping you use for orb commands.
Steps
- Add a
commands:block at the top level (requiresversion: 2.1). - Give the command a
steps:list and declareparameters:for the variable parts. - Invoke it inside a job as a step, passing any parameters as keys.
Config
.circleci/config.yml
version: 2.1
commands:
install_deps:
parameters:
cache_key:
type: string
default: deps
steps:
- restore_cache:
keys:
- << parameters.cache_key >>-{{ checksum "package-lock.json" }}
- run: npm ci
- save_cache:
key: << parameters.cache_key >>-{{ checksum "package-lock.json" }}
paths: [~/.npm]
jobs:
test:
docker:
- image: cimg/node:20.11
steps:
- checkout
- install_deps
- run: npm testGotchas
- Commands need
version: 2.1; on 2.0 config thecommands:key fails schema validation. - Reference parameters with
<< parameters.name >>, not the${{ }}syntax used by other CI systems.
Related guides
How to Use pre-steps and post-steps in CircleCIInject setup and teardown around a reusable CircleCI job using pre-steps and post-steps when invoking it in a…
How to Use YAML Anchors in a CircleCI ConfigReduce duplication in a CircleCI config with YAML anchors and aliases, defining a block once with & and reusi…