Skip to content

Reuse Custom Templates

Eric Ribeiro edited this page Jan 17, 2022 · 2 revisions

Reusing Custom Templates

While you can provide a custom template via the custom parameter, these custom templates are not reusable and add many lines to your config.

If you have created a custom template that you wish to use in multiple projects, it is possible to share the template and reduce the amount of lines added to your config using Contexts.

What is a Context?

A Context on CircleCI is a "bucket" of environment variables that can be injected in your jobs across multiple projects.


1. Generate the template.

Begin by designing your desired template.

Utilize the Block Kit Builder from slack to quickly and easily, visually design the desired notification message. When complete, copy the generated code to your clipboard.

Note: You can reference environment variables (example: ${CIRCLE_JOB}) in the template directly and they will be populated at run-time.

2. Create a Context for your Slack templates.

Follow the CircleCI docs to create a Context, and give your Context a name such as slack-templates.

Create a context for Slack templates

3. Add template to Context.

Now you can create environment variables containing your Slack template JSON that was copied earlier. The name you give the environment variable will be the name of the template.

Create a context for Slack templates

4. Use your Slack templates.

Contexts are added to jobs via your workflow, and you can add as many as you need. Any job with the context we have created here will be able to access these templates via the template parameter using the name of the environment variable for that template.

Here is a full example.

version: '2.1'
orbs:
  slack: circleci/[email protected]
jobs:
  my-job:
    docker:
      - image: 'cimg/base:stable'
    steps:
      - slack/notify:
          event: always
          template: MY_SLACK_TEMPLATE
          channel: ABCXYZ
workflows:
  my-workflow:
    jobs:
      - my-job:
          context: slack-templates

The templates within slack-templates can now be imported this way in all projects within the organization.