Skip to content

CircleCI Cheatsheet

CircleCI Cheatsheet

Installation

PlatformCommand
Linux (curl)curl -fLSs https://raw.githubusercontent.com/CircleCI-Public/circleci-cli/master/install.sh | bash
Linux (snap)sudo snap install circleci
macOS (Homebrew)brew install circleci
macOS (curl)curl -fLSs https://raw.githubusercontent.com/CircleCI-Public/circleci-cli/master/install.sh | bash
Windows (Chocolatey)choco install circleci-cli
Windows (Scoop)scoop install circleci
Verify Installationcircleci version
Initial Setupcircleci setup
Update CLIcircleci update

Basic Commands

CommandDescription
circleci config validateValidate your .circleci/config.yml file
circleci config validate -c path/to/config.ymlValidate a specific config file
circleci config process .circleci/config.ymlProcess and expand configuration (resolve orbs)
circleci local executeExecute a job locally using Docker
circleci local execute --job job-nameExecute a specific job locally
circleci followList all followed projects
circleci follow github/org/repoFollow a specific project
circleci project info github/org/repoGet project information
circleci pipeline run github/org/repoTrigger a new pipeline
circleci pipeline run github/org/repo --branch developTrigger pipeline on specific branch
circleci pipeline list github/org/repoList recent pipelines for a project
circleci pipeline get <pipeline-id>Get details about a specific pipeline
circleci build list github/org/repoList recent builds for a project
circleci build get <build-number>Get information about a specific build
circleci build cancel <build-number>Cancel a running build

Advanced Usage

CommandDescription
circleci pipeline run github/org/repo --parameters '{"key":"value"}'Trigger pipeline with parameters
circleci local execute --env VAR1=value1 --env VAR2=value2Execute locally with environment variables
circleci context list github org-nameList all contexts for an organization
circleci context create github org-name context-nameCreate a new context
circleci context show github org-name context-nameShow context details
circleci context delete github org-name context-nameDelete a context
circleci context env-var list github org-name context-nameList environment variables in a context
circleci context env-var store github org-name context-name VAR_NAMEStore environment variable in context
circleci orb listList all available public orbs
circleci orb search <query>Search for orbs by keyword
circleci orb info namespace/orb@versionGet detailed information about an orb
circleci orb source namespace/orb@versionView the source code of an orb
circleci orb create namespace/orbCreate a new orb
circleci orb publish path/to/orb.yml namespace/orb@dev:firstPublish development version of an orb
circleci orb publish promote namespace/orb@dev:first patchPromote orb to production (patch version)
circleci orb validate path/to/orb.ymlValidate an orb configuration
circleci api graphql-query --query '{ me { id name } }'Execute GraphQL API query
circleci api get /meMake REST API GET request
circleci diagnosticRun diagnostic checks on CLI setup
circleci config pack src/ > orb.ymlPack orb source files into single YAML

Configuration

Basic Configuration File Structure

The CircleCI configuration file is located at .circleci/config.yml in your repository root.

version: 2.1

# Define reusable execution environments
executors:
  node-executor:
    docker:
      - image: cimg/node:18.16
    resource_class: medium
    working_directory: ~/project

# Define reusable command sequences
commands:
  install-deps:
    steps:
      - restore_cache:
          keys:
            - v1-deps-{{ checksum "package-lock.json" }}
      - run: npm ci
      - save_cache:
          key: v1-deps-{{ checksum "package-lock.json" }}
          paths:
            - node_modules

# Define jobs
jobs:
  build:
    executor: node-executor
    steps:
      - checkout
      - install-deps
      - run: npm run build
      - persist_to_workspace:
          root: .
          paths:
            - dist

  test:
    executor: node-executor
    steps:
      - checkout
      - install-deps
      - run: npm test
      - store_test_results:
          path: test-results

# Define workflows
workflows:
  build-and-test:
    jobs:
      - build
      - test:
          requires:
            - build

Docker Executor Configuration

jobs:
  build:
    docker:
      - image: cimg/python:3.11
        auth:
          username: $DOCKERHUB_USERNAME
          password: $DOCKERHUB_PASSWORD
        environment:
          FLASK_ENV: development
      - image: cimg/postgres:14.0
        environment:
          POSTGRES_USER: testuser
          POSTGRES_DB: testdb
    resource_class: large
    steps:
      - checkout
      - run: python app.py

Machine Executor Configuration

jobs:
  build:
    machine:
      image: ubuntu-2204:2023.04.2
      docker_layer_caching: true
    resource_class: large
    steps:
      - checkout
      - run: docker build -t myapp .

Using Orbs

version: 2.1

orbs:
  node: circleci/node@5.1.0
  aws-cli: circleci/aws-cli@3.1.0
  slack: circleci/slack@4.12.0

jobs:
  deploy:
    executor: node/default
    steps:
      - checkout
      - node/install-packages
      - aws-cli/setup
      - run: npm run deploy
      - slack/notify:
          event: pass
          template: success_tagged_deploy_1

Workflow Filters and Scheduling

workflows:
  version: 2
  build-deploy:
    jobs:
      - build
      - test:
          requires:
            - build
      - deploy:
          requires:
            - test
          filters:
            branches:
              only:
                - main
                - /release\/.*/
            tags:
              only: /^v.*/
  
  nightly:
    triggers:
      - schedule:
          cron: "0 0 * * *"
          filters:
            branches:
              only: main
    jobs:
      - test

Parallelism and Test Splitting

jobs:
  test:
    docker:
      - image: cimg/node:18.16
    parallelism: 4
    steps:
      - checkout
      - run: npm ci
      - run:
          name: Run Tests
          command: |
            TESTFILES=$(circleci tests glob "tests/**/*.test.js" | \
                        circleci tests split --split-by=timings)
            npm test $TESTFILES
      - store_test_results:
          path: test-results

Resource Classes

jobs:
  small-job:
    docker:
      - image: cimg/base:stable
    resource_class: small  # 1 vCPU, 2GB RAM
  
  large-job:
    docker:
      - image: cimg/base:stable
    resource_class: large  # 4 vCPU, 8GB RAM
  
  xlarge-job:
    docker:
      - image: cimg/base:stable
    resource_class: xlarge  # 8 vCPU, 16GB RAM

Common Use Cases

Use Case 1: Multi-Stage Node.js Application Pipeline

version: 2.1

orbs:
  node: circleci/node@5.1.0

jobs:
  build:
    executor: node/default
    steps:
      - checkout
      - node/install-packages:
          pkg-manager: npm
      - run:
          name: Build Application
          command: npm run build
      - persist_to_workspace:
          root: .
          paths:
            - dist
            - node_modules

  test:
    executor: node/default
    steps:
      - checkout
      - attach_workspace:
          at: .
      - run:
          name: Run Unit Tests
          command: npm test
      - store_test_results:
          path: test-results

  deploy-staging:
    executor: node/default
    steps:
      - attach_workspace:
          at: .
      - run:
          name: Deploy to Staging
          command: npm run deploy:staging

workflows:
  build-test-deploy:
    jobs:
      - build
      - test:
          requires:
            - build
      - deploy-staging:
          requires:
            - test
          filters:
            branches:
              only: develop

Use Case 2: Docker Image Build and Push

version: 2.1

orbs:
  docker: circleci/docker@2.2.0

jobs:
  build-and-push:
    executor: docker/docker
    steps:
      - setup_remote_docker:
          docker_layer_caching: true
      - checkout
      - docker/check
      - docker/build:
          image: myorg/myapp
          tag: ${CIRCLE_SHA1},latest
      - docker/push:
          image: myorg/myapp
          tag: ${CIRCLE_SHA1},latest

workflows:
  build-deploy:
    jobs:
      - build-and-push:
          context: docker-hub-creds
          filters:
            branches:
              only: main

Use Case 3: Parallel Testing with Test Splitting

version: 2.1

jobs:
  test:
    docker:
      - image: cimg/python:3.11
    parallelism: 8
    steps:
      - checkout
      - run: pip install -r requirements.txt
      - run:
          name: Run Tests in Parallel
          command: |
            TESTFILES=$(circleci tests glob "tests/**/test_*.py" | \
                        circleci tests split --split-by=timings)
            pytest $TESTFILES \
              --junitxml=test-results/junit.xml \
              --cov=app \
              --cov-report=html
      - store_test_results:
          path: test-results
      - store_artifacts:
          path: htmlcov

workflows:
  test:
    jobs:
      - test

Use Case 4: Conditional Workflow with Parameters

version: 2.1

parameters:
  run-integration-tests:
    type: boolean
    default: false
  deployment-environment:
    type: string
    default: "staging"

jobs:
  unit-test:
    docker:
      - image: cimg/node:18.16
    steps:
      - checkout
      - run: npm ci
      - run: npm run test:unit

  integration-test:
    docker:
      - image: cimg/node:18.16
    steps:
      - checkout
      - run: npm ci
      - run: npm run test:integration

  deploy:
    docker:
      - image: cimg/node:18.16
    parameters:
      environment:
        type: string
    steps:
      - checkout
      - run: npm ci
      - run: npm run deploy:<< parameters.environment >>

workflows:
  test-and-deploy:
    jobs:
      - unit-test
      - integration-test:
          when: << pipeline.parameters.run-integration-tests >>
      - deploy:
          environment: << pipeline.parameters.deployment-environment >>
          requires:
            - unit-test
          filters:
            branches:
              only: main

Use Case 5: Monorepo with Path Filtering

version: 2.1

setup: true

orbs:
  path-filtering: circleci/path-filtering@0.1.3

workflows:
  setup-workflow:
    jobs:
      - path-filtering/filter:
          base-revision: main
          config-path: .circleci/continue-config.yml
          mapping: |
            services/api/.* api-build true
            services/web/.* web-build true
            packages/.* all-build true

continue-config.yml:

version: 2.1

parameters:
  api-build:
    type: boolean
    default: false
  web-build:
    type: boolean
    default: false
  all-build:
    type: boolean
    default: false

jobs:
  build-api:
    docker:
      - image: cimg/node:18.16
    steps:
      - checkout
      - run: cd services/api && npm ci && npm run build

  build-web:
    docker:
      - image: cimg/node:18.16
    steps:
      - checkout
      - run: cd services/web && npm ci && npm run build

workflows:
  api-workflow:
    when: << pipeline.parameters.api-build >>
    jobs:
      - build-api

  web-workflow:
    when: << pipeline.parameters.web-build >>
    jobs:
      - build-web

Best Practices

  • Use Orbs for Common Tasks: Leverage CircleCI orbs for standardized integrations (AWS, Docker, Slack) to reduce configuration complexity and maintenance burden.

  • Implement Caching Strategically: Cache dependencies using checksum-based keys ({{ checksum "package-lock.json" }}) to speed up builds while ensuring cache invalidation when dependencies change.

  • Optimize Resource Classes: Choose appropriate resource classes for each job; use smaller instances for simple tasks and reserve larger instances for compute-intensive operations like compilation or complex tests.

  • Enable Docker Layer Caching: For jobs that build Docker images, enable docker_layer_caching: true to significantly reduce build times by reusing unchanged layers.

  • Split Tests for Parallel Execution: Use circleci tests split with --split-by=timings to distribute tests across parallel containers based on historical execution times, maximizing efficiency.

  • Use Workspaces for Inter-Job Data: Persist build artifacts using persist_to_workspace and attach_workspace instead of re-building in subsequent jobs, saving time and ensuring consistency.

  • Implement Workflow Filters: Use branch and tag filters to control when jobs run, preventing unnecessary deployments and conserving credits while maintaining security.

  • Store Secrets in Contexts: Manage sensitive credentials in CircleCI contexts rather than project environment variables for better security, access control, and reusability across projects.

  • Validate Configuration Locally: Always run circleci config validate and test jobs locally with circleci local execute before pushing to catch syntax errors and configuration issues early.

  • Monitor and Optimize Credit Usage: Regularly review Insights and Analytics to identify slow jobs, optimize parallelism settings, and reduce unnecessary workflow runs to manage costs effectively.

Troubleshooting

IssueSolution
”Config file not found” errorEnsure .circleci/config.yml exists in repository root. Run circleci config validate to check file location and syntax.
Local execution fails with Docker errorsVerify Docker is running: docker ps. Ensure the CLI has access to Docker socket. On Linux, add user to docker group: sudo usermod -aG docker $USER.
”Invalid configuration” during validationRun circleci config process .circleci/config.yml to see expanded config and identify syntax errors. Check YAML indentation (use spaces, not tabs).
Jobs not triggering on pushVerify project is followed: circleci follow github/org/repo. Check workflow filters aren’t excluding your branch. Ensure webhook is configured in VCS settings.
Workspace attachment failsEnsure persist_to_workspace in upstream job completes successfully. Verify root and paths match between persist and attach. Check job dependencies in workflow.
Cache not restoringVerify cache key matches between save_cache and restore_cache. Use fallback keys: keys: [v1-{{ checksum "file" }}, v1-]. Check cache hasn’t expired (30 days).
Authentication errors with CLIRe-run circleci setup with a valid API token. Generate new token at https://app.circleci.com/settings/user/tokens. Verify token has correct permissions.
Parallel test splitting not workingEnsure test results are stored with store_test_results. Use glob patterns that match your test files. Verify parallelism is set greater than 1.
Out of memory errorsIncrease resource_class to large or xlarge. Optimize memory-intensive operations. Check for memory leaks in application code.
Context environment variables not availableVerify job uses correct context in workflow: context: context-name. Check user has access to context in organization settings. Ensure variable names don’t conflict.
Orb import failsVerify orb exists: circleci orb info namespace/orb@version. Check version is valid. For private orbs, ensure organization has access and use --org-id flag.
SSH debugging session won’t connectAdd - run: circleci-agent step halt in config where you want to pause. Rerun job with SSH enabled. Use provided SSH command within 10 minutes before timeout.